【问题标题】:How to create React components that accept color as parameter?如何创建接受颜色作为参数的 React 组件?
【发布时间】:2018-08-04 02:19:38
【问题描述】:

假设我想使用 react 创建一个自定义按钮。我想让这个组件接受颜色作为它的属性,并根据属性中的颜色呈现自己。

class MyButton extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { name, color } = this.props;

    return (
      <div className="my-button">
        <button type="button" className="btn">
          {name}
        </button>
      </div>
    );
  }
}

如何将color 注入按钮css 样式(边框和字体颜色)?

【问题讨论】:

  • 类似&lt;button style={{borderColor: color}}&gt;

标签: javascript css reactjs


【解决方案1】:

使用类似的东西:

编辑:也添加了边框颜色的代码

class MyButton extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { name, color } = this.props;

    return (
      <div className="my-button">
        <button type="button" className="btn" 
          style={{
             color,
             borderColor:color
                 }}>
          {name}
        </button>
      </div>
    );
  }
}

【讨论】:

  • 这可能不起作用,因为 'color' 只是一种纯色,而不是 css 样式。
  • color prop 是什么类型的对象?它不是一个 css 有效值(如“white”、“rgb(250,123,234)”等)吗?
  • 是的,是彩串
  • 那不用担心,有一些有效的css颜色字符串,你可以毫无问题地使用它们。见:link
【解决方案2】:

尽量不要使用内联 CSS。最好有课

  .btn-primary: {
      color: blue;
  }

这是你的按钮。

class MyButton extends React.Component {
  constructor(props) {
     super(props);
  }

  render() {
    const { name, classNameProp } = this.props;

    return (
      <div className="my-button">
        <button type="button" className={"btn "+ (classNameProp ? classNameProp : '')}>
          {name}
        </button>
      </div>
    );
  }
}

而你是这样使用它的。

<MyButton classNameProp="btn-primary"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-18
    • 2021-10-30
    • 2014-02-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    相关资源
    最近更新 更多