【问题标题】:React, add css class from props [duplicate]反应,从道具添加css类[重复]
【发布时间】:2020-04-24 09:33:33
【问题描述】:

我正在尝试向我的 Card 组件添加一个类,以便在插入时可以选择布局。但是在className中没有解释props,我怎样才能这样添加一个css类?

组件

 function Card(props) {
        return (
          <div className="d-flex mx-auto {props.layout}" >
            <div className="background my-auto">
              <div className="d-flex justify-content-center">
                <h3>{props.title}</span></h3>
              </div>
              <div className="d-flex h-100">
                <div className="w-100 my-auto">
                  <p>{props.text}</p>
                </div>
              </div>
            </div>
          </div>
        );
      }

在布局中

<Card
 layout="my-green-bg"
 title="my title"
 text="my text"
/>

【问题讨论】:

  • className={`d-flex mx-auto ${props.layout}`}

标签: javascript reactjs react-props


【解决方案1】:

尝试以下方法:

<div className={`d-flex mx-auto ${props.layout}`}>

或者没有模板文字:

<div className={'d-flex mx-auto ' + props.layout}>

我希望这会有所帮助!

【讨论】:

    【解决方案2】:

    你可以试试下面的代码。

    function Card(props) {
        const classes = [ 'd-flex', 'mx-auto' ];
        if (props.layout) classes.push(props.layout);
            return (
              <div className={ classes.join(' ') } >
                <div className="background my-auto">
                  <div className="d-flex justify-content-center">
                    <h3>{props.title}</span></h3>
                  </div>
                  <div className="d-flex h-100">
                    <div className="w-100 my-auto">
                      <p>{props.text}</p>
                    </div>
                  </div>
                </div>
              </div>
            );
          }
    

    另一种方法是

    function Card(props) {
            return (
              <div className={ 'd-flex mx-auto ' + props.layout } >
                <div className="background my-auto">
                  <div className="d-flex justify-content-center">
                    <h3>{props.title}</span></h3>
                  </div>
                  <div className="d-flex h-100">
                    <div className="w-100 my-auto">
                      <p>{props.text}</p>
                    </div>
                  </div>
                </div>
              </div>
            );
          }
    

    【讨论】:

      猜你喜欢
      • 2018-06-04
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2014-07-05
      • 1970-01-01
      • 2017-08-16
      相关资源
      最近更新 更多