[英]ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>'
I'm trying to change the name property of an input as the state of my component changes.我正在尝试更改输入的名称属性,因为我的组件的 state 发生了变化。
in short, this is What i'm trying to do.简而言之,这就是我想要做的。
let displayInputElement = (
<input
type="text"
name = {pips}
placeholder="Type your answer here"
className=" form-control"
/>
);
displayInputElement.props.name = "chicken";
But I'm getting the below error但我收到以下错误
TypeError: Cannot assign to read only property 'name' of object '#'
类型错误:无法分配给 object '#' 的只读属性“名称”
Please how can i achieve the below in react请我如何在反应中实现以下目标
displayInputElement.props.name = "chicken";
let pips = displayInputElement.props.name;
displayInputElement = (
<input
type="text"
name = "chicken"
placeholder="Type your answer here"
className=" form-control"
/>
);
I think you should make displayInputElement as a component so you can pass whatever you want through the props argument我认为你应该把 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);
You can't set props by writing DisplayInputElement.props.name="chicken"
as props are meant to be read.您不能通过编写
DisplayInputElement.props.name="chicken"
来设置道具,因为道具是要读取的。 I have just taken an example state to demonstrate what I mean.我刚刚举了一个例子来说明我的意思。 Hope this helps you.
希望这对你有帮助。
Props are read only.道具是只读的。
You can create a new variable with the name prop, then change that variable, or, use a callback to update the parent component's property which can be passed down to this component.您可以创建一个名为 prop 的新变量,然后更改该变量,或者使用回调来更新可以传递给该组件的父组件的属性。
let newName = displayInputElement.props.name;
newName = "chicken";
Or something like this:或者像这样:
this.state = {
name: this.props.name;
}
this.setState({
name: "chicken";
}), () => {
callbackToParent(this.state.name);
}
I was facing the same issue while working with React State.我在使用 React State 时遇到了同样的问题。 I have found the simple solution and its worked for me.
我找到了简单的解决方案,它对我有用。 Just you will have to do a deep copy of your array.
只是你必须对你的数组做一个深拷贝。 It may be enough with:
这可能就足够了:
let newData = data.map((item) =>
Object.assign({}, item, {selected:false})
)
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.