我正在尝试在组件状态发生变化时更改输入的名称属性。
简而言之,这就是我正在尝试做的事情。
let displayInputElement = (
<input
type="text"
name = {pips}
placeholder="Type your answer here"
className=" form-control"
/>
);
displayInputElement.props.name = "chicken";
但是我收到以下错误
TypeError: Cannot assign to read only property 'name' of object '#'
请问我如何在 react 中实现以下目标
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"
来设置 props,因为 props 是用来读取的。
我刚刚举了一个例子来说明我的意思。希望这对您有帮助。
关于javascript - ReactJs类型错误: Cannot assign to read only property 'name' of object '#<Object>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440637/