假设我有一个具有 className 的 ReactElement,并且我想向其 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 公共(public) API 的一部分并且应该在未来保持兼容吗?我在文档中找不到这个。

还有其他方法可以实现这一目标吗?

请您参考如下方法:

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

如果您进行大量的 className 操作,我建议使用 classnames模块。

您之前的示例将变为:

var cx = require('classnames'); 
 
React.cloneElement(hello2, { 
  className: cx(hello2.props.className, "test1"), 
}); 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!