简体   繁体   中英

How can I prevent from mutating the style object in a div?

I am getting the following error:

Warning: div was passed a style object that has previously been mutated. Mutating style is deprecated. Consider cloning it beforehand. Check the render of Tab . Previous style: {padding: "20px", display: "block"} . Mutated style: {padding: "20px", display: "none"} .

From this code in my render() method in React/JSX:

const clonedChildren = React.Children.map(this.props.children, (el, i) => {
  let visibility = 'none';
  if (i === this.state.activeIndex) visibility = 'block';
  const newStyle = { display: visibility };
  const style = Object.assign(el.props.style, newStyle);
  return React.cloneElement(el, { style });
});

Why is this error happening? I am already cloning the element. How can I fix this?

Don't mutate your el.props.style . Currently you're using Object.assign and mutating el.props.style by using it as the target object. Instead, use Object.assign and use a new object as the target:

const style = Object.assign({}, el.props.style, newStyle);

This will not mutate el.props.style . It will instead mutate the new object {} . Further reading on Object.assign at MDN .

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