React.cloneElement - >添加className元素

时间:2015-10-30 11:35:31

标签: reactjs

假设我有一个ReactElement,它有一个className,我想在其className中添加一个新类,而不会覆盖现有的className。 我该怎么做?

我已经尝试了以下操作,但确实覆盖了现有的className:

var hello = <Hello name="World" className="base"/>;
hello = React.cloneElement(hello,{className: "text1"});
hello = React.cloneElement(hello,{className: "text2"});

然而,此解决方案有效:

var hello2 = <Hello name="World" className="base"/>;
hello2 = React.cloneElement(hello2,{className: hello2.props.className + " test1"});
hello2 = React.cloneElement(hello2,{className: hello2.props.className + " test2"});

但这样使用ReactElement.props是否安全?它是ReactElement的公共API的一部分,并且应该在将来保持反向兼容吗?我无法在文档中找到它。

还有另一种方法可以达到这个目的吗?

2 个答案:

答案 0 :(得分:11)

React元素的结构是稳定的,请参阅Nodes and Elements,因此您的方法是完全安全的(并推荐)。

如果你进行了很多className操作,我建议使用classnames模块。

您之前的示例将变为:

var cx = require('classnames');

React.cloneElement(hello2, {
  className: cx(hello2.props.className, "test1"),
});

答案 1 :(得分:-3)

CloneElement很慢,看起来有点矫枉过正。你可以使用mixin来做这个和npm classnames包(https://www.npmjs.com/package/classnames)。

var classNames = require('classnames');

一个函数,用于添加类字符串或转换为对象(见下文),以便像在文档中那样传递给classNames

classNames('foo','bar'); // =&gt; 'foo bar'

classNames({foo:true},{bar:false}); // =&gt; '富'

相关问题