Ank*_*hal 15 javascript object reactjs
我正在我的组件中接收道具。我想在这个组件中添加一个带有道具的属性“LegendPosition”。我无法做到这一点。请帮我解决一下这个。我已经尝试过这段代码,但没有成功:
var tempProps = this.props;
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);
console.log(tempProps);
Run Code Online (Sandbox Code Playgroud)
Mah*_*Ali 16
你不能修改this.props. 这tempProps是参考,this.props所以它不起作用。您应该创建一个propsusingJSON.parse()和JSON.stringify()
var tempProps = JSON.parse(JSON.stringify(this.props));
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);
console.log(tempProps);
Run Code Online (Sandbox Code Playgroud)
有关深度克隆对象的更好更有效的方法,请参阅在 JavaScript 中深度克隆对象的最有效方法是什么?
Joe*_*oey 10
props 是不可变的,你不能向它们“添加”任何东西。如果你想“复制”它们那么你需要这样做
const tempProps = {...this.props};
Run Code Online (Sandbox Code Playgroud)
我看到您需要添加更多道具的唯一原因是将其传递给孩子,但您可以在不将其添加到道具对象的情况下做到这一点。
编辑:添加带有额外道具的道具
<Component {...this.props} legendPosition="right" />
Run Code Online (Sandbox Code Playgroud)