传递类名以响应组件

JavaScript

Harry小胖

2020-03-12

我试图将类名传递给react组件以更改其样式,但似乎无法正常工作:

class Pill extends React.Component {

  render() {

    return (
      <button className="pill {this.props.styleName}">{this.props.children}</button>
    );
  }

}

<Pill styleName="skill">Business</Pill>

我正在尝试通过传递具有相应样式的类的名称来更改药丸的样式。我是React的新手,所以也许我做的方式不正确。谢谢

第1346篇《传递类名以响应组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
Eva小胖 2020.03.13

借助React对字符串插值的支持,您可以执行以下操作:

class Pill extends React.Component {
    render() {
       return (
          <button className={`pill ${this.props.styleName}`}>{this.props.children}</button>
       );
    }
}

飞云西里神乐 2020.03.13

您可以使用来“内插”从父组件传递到子组件的className来实现this.props.className下面的例子:

export default class ParentComponent extends React.Component {
  render(){
    return <ChildComponent className="your-modifier-class" />
  }
}

export default class ChildComponent extends React.Component {
  render(){
    return <div className={"original-class " + this.props.className}></div>
  }
}
蛋蛋十三 2020.03.13

pill ${this.props.styleName} 当您不设置道具时,将得到“药丸未定义”

我更喜欢

className={ "pill " + ( this.props.styleName || "") }

要么

className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android