如何防止 div 中的样式对象发生变异?

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

我收到以下错误:

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"}.

来自 React/JSX 中我的 render() 方法中的这段代码:

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

为什么会出现这个错误?我已经在克隆元素了。我该如何解决这个问题?

不要改变你的 el.props.style。当前,您正在使用 Object.assign 并通过将其用作目标对象来改变 el.props.style。相反,使用 Object.assign 并使用一个新对象作为目标:

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

这不会变异 el.props.style。相反,它会改变新对象 {}。在 MDN.

进一步阅读 Object.assign