简体   繁体   中英

React.cloneElement in List performance

I have doubts about React.cloneElement in List. Is that something that we should avoid doing or not, if we have lots of elements in list? Does React.cloneElement makes unnecessary re-renders that could be avoided?

My component:

...
      render() {
        const { items, classes, children } = this.props;
        const { expanded } = this.state;
        return (
          <List className={classes.cssRoot}>
            <Scrollbars
              style={classes.cssScrollBar}
              renderThumbVertical={this.renderThumb}
            >
              {items.map((item, index) => {
                return (
                  <ListItem key={item.id} className={classes.cssListItemRoot}>
                    {React.Children.map(children, child =>
                      React.cloneElement(child, {
                        id: item.id,
                        name: `Item nummber ${index}`,
                        handleChange: this.handleChange,
                        isExpanded: expanded === item.id
                      })
                    )}
                  </ListItem>
                );
              })}
            </Scrollbars>
          </List>
        );
      }
...

Seeing React.cloneElement in the middle of some JSX can look a little scary and unfamiliar, but it is very benign from a performance standpoint. The thing to realize is that JSX gets transformed into calls to React.createElement which just returns an object. React.cloneElement is just copying that object and allowing you to modify props in the process. The resulting object will look no different to React than the original object created via JSX aside from the prop changes, and it has no harmful effects as far as causing extra renders. The performance impacts are of no more concern than if you had a function that was transforming some data by taking in an array of objects and creating a new array with copies of those objects with an additional property.

Material-UI leverages React.cloneElement internally in a number of places to add in additional props to children such as in Radio.js .

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