![](/img/trans.png)
[英]TypeError: Cannot assign to read only property 'exports' of object '#<Object>' in ReactJS
[英]ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>'
我正在尝试更改输入的名称属性,因为我的组件的 state 发生了变化。
简而言之,这就是我想要做的。
let displayInputElement = (
<input
type="text"
name = {pips}
placeholder="Type your answer here"
className=" form-control"
/>
);
displayInputElement.props.name = "chicken";
但我收到以下错误
类型错误:无法分配给 object '#' 的只读属性“名称”
请我如何在反应中实现以下目标
displayInputElement.props.name = "chicken";
let pips = displayInputElement.props.name;
displayInputElement = (
<input
type="text"
name = "chicken"
placeholder="Type your answer here"
className=" form-control"
/>
);
我认为你应该把 displayInputElement 作为一个组件,这样你就可以通过 props 参数传递你想要的任何东西
let DisplayInputElement = (props) =>(
<input
type="text"
name = {props.name}
placeholder="Type your answer here"
className=" form-control"
/>
);
const state = {
name:"myrrtle"
}
ReactDOM.render(<DisplayInputElement name={state.name} />, mountNode);
您不能通过编写DisplayInputElement.props.name="chicken"
来设置道具,因为道具是要读取的。 我刚刚举了一个例子来说明我的意思。 希望这对你有帮助。
道具是只读的。
您可以创建一个名为 prop 的新变量,然后更改该变量,或者使用回调来更新可以传递给该组件的父组件的属性。
let newName = displayInputElement.props.name;
newName = "chicken";
或者像这样:
this.state = {
name: this.props.name;
}
this.setState({
name: "chicken";
}), () => {
callbackToParent(this.state.name);
}
我在使用 React State 时遇到了同样的问题。 我找到了简单的解决方案,它对我有用。 只是你必须对你的数组做一个深拷贝。 这可能就足够了:
let newData = data.map((item) =>
Object.assign({}, item, {selected:false})
)
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.