【问题标题】:React.cloneElement -> Add className elementReact.cloneElement -> 添加 className 元素
【发布时间】:2015-10-30 11:35:31
【问题描述】:

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

我尝试了以下方法,但它确实覆盖了现有的类名:

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 的一部分,并且应该在未来保持向后兼容吗?我在文档中找不到这个。

还有其他方法可以实现吗?

【问题讨论】:

  • 改用共享变量? :P 我认为 ReactElement 将来会有道具是一个相当安全的赌注

标签: javascript reactjs


【解决方案1】:

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

如果你做了很多类名操作,我推荐使用classnames 模块。

你之前的例子会变成:

var cx = require('classnames');

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

【讨论】:

  • 因为是的,我已经使用了它,但从未使用过除了 react 插件之外的任何东西
【解决方案2】:

CloneElement 速度很慢,看起来有点矫枉过正。您可以使用 mixin 和 npm 类名包 (https://www.npmjs.com/package/classnames) 来执行此操作。 沿着

var classNames = require('classnames');

添加类字符串或转换为对象(见下文)以传递给文档中的类名的函数

classNames('foo', 'bar'); // => '富酒吧'

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

【讨论】:

  • 这应该是一个答案吗?还是另一个问题?
  • 这是一种替代方法的建议,而不是问题 - 你有什么建设性的要说吗?
  • 询问这是否是一个答案是一个合法的问题。提出问题或在答案中发表评论(在我看来就是这样)没有帮助。你的意思是说If you can use a mixin and the npm classnames package then you can do this: ...
猜你喜欢
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多