簡體   English   中英

如何創建接受顏色作為參數的React組件?

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

假設我想使用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樣式(邊框和字體顏色)?

使用類似:

編輯:也添加了邊框顏色代碼

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

盡量不要使用內聯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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM