简体   繁体   English

如何创建接受颜色作为参数的React组件?

[英]How to create React components that accept color as parameter?

Assume that I want to create a customized button using react. 假设我想使用react创建一个自定义按钮。 And I'd like to have this component accept color as its properties and render itself based on the color from the properties. 我想让该组件接受颜色作为其属性,并根据属性中的颜色进行渲染。

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>
    );
  }
}

How can I inject the color into the button css style (border and font color)? 如何将color注入按钮CSS样式(边框和字体颜色)?

Use something like: 使用类似:

EDIT: Added code for border color too 编辑:也添加了边框颜色代码

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>
    );
  }
}

Try not to use inline css. 尽量不要使用内联CSS。 Its better to have a class 最好去上课

  .btn-primary: {
      color: blue;
  }

And here is your button. 这是您的按钮。

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>
    );
  }
}

And you use it like this. 然后您像这样使用它。

<MyButton classNameProp="btn-primary"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM