![](/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.