简体   繁体   中英

React.cloneElement -> Add className element

Suppose I have a ReactElement that has a className, and I want to add a new class to its className, without overriding the existing className. How am I supposed to do this?

I've tried the following but it does override the existing className:

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

However this solution works:

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"});

But is this safe to use ReactElement.props like that? Is it part of the public API of a ReactElement and is supposed to be kept retrocompatible in the future? I was not able to find this in the documentation.

Is there another way to achieve this?

The structure of React elements is stable, see Nodes and Elements , so your approach is completely safe (and recommended).

If you do a lot of className manipulation, I recommend using the classnames module.

Your previous example would then become:

var cx = require('classnames');

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

CloneElement is slow and seems like overkill. Can you use a mixin to do this and npm classnames package ( https://www.npmjs.com/package/classnames ). Along the lines of

var classNames = require('classnames');

a function to add the class strings or convert into an object (see below) to hand off to classNames as in the docs

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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