繁体   English   中英

React.cloneElement->添加className元素

[英]React.cloneElement -> Add className element

假设我有一个具有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的公共API的一部分,并且应该在以后保持兼容? 我在文档中找不到此内容。

还有另一种方法可以做到这一点吗?

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

如果您做了很多className操作,建议您使用classnames模块。

您先前的示例将变为:

var cx = require('classnames');

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

CloneElement速度慢,似乎有点过大。 您可以使用mixin和npm classnames软件包( https://www.npmjs.com/package/classnames )来执行此操作。 沿线

var classNames = require('classnames');

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

classNames('foo','bar'); // =>'foo bar'

classNames({foo:true},{bar:false}); // =>'foo'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM