next.js 如何在react中为一个组件添加不同的样式

kq0g1dla  于 2023-04-30  发布在  React
关注(0)|答案(2)|浏览(147)

我试图在react nect中为一个组件添加不同的样式。下面我提到了我的按钮组件代码
import styles from "./button.module.css"; const Button = props =>{ return( <div> <button className={styles.button}>{props.text}</button> </div> ) } export default Button;
我必须在我的网页中使用这个按钮组件两次,但风格不同。(例如,我希望第一个组件具有蓝色背景,另一个组件具有绿色背景。有人能帮我吗?

import Button from "@/components/button";
function Home() {
  return (
    <div className="home">
      <div className="actions">
        <Button className="live" text = "Go Live"/>
        <Button className="userAdd" text = "Add users"/>
      </div>
    </div>
  );
}
export default Home;

我尝试为按钮组件添加不同的类名,并为该类添加样式。但没有结果。

cczfrluj

cczfrluj1#

有几种方法:

方法一

将颜色作为 prop 传递给Button。这里我有一个名为.button的基类(包含所有类型按钮的填充/边距信息),我将其与Button组件中的数组中的colour类组合在一起,并将其传递给button className属性。
注意:如果你的类组合对于数组来说太笨拙,你可以使用classnames实用程序库而不是数组。
button.modules.css

.button { padding: 0.4em; }
.blue { background-color: blue; }
.green { background-color: green; }

Button.jsx

function Button({ text, color }) {
  
  const cn = [
    style.button,
    style[color]
  ].join(' ');
  
  return (
    <button className={cn} type="button">
      {text}
    </button>
  );

}

function Example() {
  return (
    <section>
      <Button text="Go live" color="blue" />
      <Button text="Add users" color="green" />
    </section>
  );
}
方法二

非常相似,但使用composes在每个颜色类中使用.button基类继承其属性。这意味着您不必使用数组来构建className。
button.modules.css

.button { padding: 0.4em; }
.blue { composes: button; background-color: blue; }
.green { composes: button; background-color: green; }

Button.jsx

function Button({ text, color }) {      
  return (
    <button className={style[color]} type="button">
      {text}
    </button>
  );
}

function Example() {
  return (
    <section>
      <Button text="Go live" color="blue" />
      <Button text="Add users" color="green" />
    </section>
  );
}
z8dt9xmd

z8dt9xmd2#

首先,您可以让Button组件使用传入的className prop,并将其添加到基类中。您可以决定是将这些附加类应用于<button>还是父<div>

const Button = ({className = '', text}) => 
        <div><button className={styles.button + ' ' + className}>{text}</button></div>;

然后,您可以向button.module.css添加更多类:

.live {
    /* ... */
}
.userAdd {
    /* ... */
}

最后,在Home组件中传递更多的类。

import buttonStyles from './button.module.css';
function Home() {
  return (
    <div className="home">
      <div className="actions">
        <Button className={buttonStyles.live} text="Go Live"/>
        <Button className={buttonStyles.userAdd} text="Add users"/>
      </div>
    </div>
  );
}

相关问题