【问题标题】:Assign two className to child将两个 className 分配给孩子
【发布时间】:2016-12-02 08:55:06
【问题描述】:

我父母的组件中有以下代码 -

<Button className={'row1 column1'} value={'1'}/>

所以我向孩子的组件发送了两个 className。 然后在我的子组件中我有

    render() {
        var { value, className, ...other} = this.props;
        return (
          <button className={s[className]}> {value} </button>
        )
      }
}
export default withStyles(s)(Button);

通常我手动设置className={s.something} 并且它有效,但事实并非如此。在呈现的 html 中,它看起来像 - &lt;button is="null"&gt;&lt;/button&gt; 有什么想法吗?

【问题讨论】:

  • 我需要和s.一起使用。最后我导出export default withStyles(s)(Button);而没有s.,className是正确的,但是css没有加载。

标签: button reactjs styles classname


【解决方案1】:

假设您使用react-with-stylewithStyles 将向您的props 添加一个styles 对象。

此对象不知道任何classNames,您只需将这些styles 作为内联样式传递给您的按钮。

例如:

render() {
  var { value, className, style, ...other} = this.props;
  return (
    <button
      className={ className }
      style={ style }
    >
      { value }
    </button>
  )
}

编辑: withStyle 的优点是使用内联样式。而且我想您的s 对象没有键row1 column1 而是row1column1,因此您需要手动拆分类名。

不过话说回来,你为什么要className 中的样式?

【讨论】:

  • 但在其他组件中,我通常有 &lt;div className={s.container}&gt; ,然后在 css 中我有类 .container{} 并且它可以工作,我不需要使用 style={}
  • 那你为什么用withStyle
  • 我在基本的反应组件中看到了它,它在状态套件中。他们有文件,包括 componentName.js,然后是 componenetName.css,在 js 中他们有相同的代码......className={s.container} 最后他们用Styles 导出......现在我想直接将样式分配给各个按钮。
  • 然后像我的例子那样做,保持 className 不变,但直接从你在 props 中获得的 styles 对象分配内联样式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
  • 2012-10-17
  • 2010-10-20
相关资源
最近更新 更多