这是我的错误示例。 我想动态添加组件 然后动态更改组件的属性。
但是……
import React from 'react';
export class Test extends React.Component {
state = { SubArray: [] }
render() {
return (
<div>
<button onClick={this.F_Add}>Add New Sub</button>
<div>{this.state.SubArray}</div>
<button onClick={this.F_ChangeA}>Change Each Value = 100,200,……</button>
<button onClick={this.F_ChangeB}>Change All value=100</button>
</div>
);
}
F_Add = () => {
let NewSub = React.createElement(Subitem, { value: 100 })
this.state.SubArray.push(NewSub)
this.setState({ SubArray: this.state.SubArray })
};
F_ChangeA = () => {
let value = 0
for (var k = 0, length = this.state.SubArray.length; k < length; k++) {
let input = this.state.SubArray[k]
value += 100
input.props.value = value //Uncaught TypeError: Cannot assign to read only property 'value' of object '#<Object>'
}
}
F_ChangeB = () => {
for (var k = 0, length = this.state.SubArray.length; k < length; k++) {
let input = this.state.SubArray[k]
input.props.value = 100 //Uncaught TypeError: Cannot assign to read only property 'value' of object '#<Object>'
}
}
}
class Subitem extends React.Component {
render() {
return (
<input type="text" value={this.props.value} />
);
}
}
但是 TypeError:无法分配为只读对象“#”的属性“ value”