javascript - 传入类名以响应组件

标签 javascript reactjs

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

class Pill extends React.Component {

  render() {

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

}

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

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

最佳答案

在 React 中,当你想传递一个解释型表达式时,你必须打开一对花括号。尝试:

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

使用 classnames npm 包

import classnames from 'classnames';

render() {
  return (
    <button className={classnames('pill', this.props.styleName)}>
      {this.props.children}
    </button>
  );
}

关于javascript - 传入类名以响应组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32230635/

相关文章:

javascript - redux 不会通过 browserHistory.push() 强制使用 mapStateToProps

reactjs - 在 react 中保存 image._id

javascript - setState(...) : Can only update a mounted or mounting component. 这通常意味着您在未安装的组件上调用了 setState()

javascript - 为什么 slice() 在函数中使用时会改变状态

javascript - 如何通过 jquery 向 <li> 添加 2 个按钮

javascript - ckeditor 在 Bootstrap 模式中打开时清除数据

javascript - 如何访问 webdriver 中添加的插件

javascript - 根据浏览器大小定位元素

javascript - 从映射数组中获取元素

reactjs - Material-UI CardContent 有一个 3px 的底部填充