【发布时间】:2018-08-14 21:53:10
【问题描述】:
这是与此相关的我的 sn-ps 代码:
家长:
class PropertyBar extends Component {
state = {
selectedCell: graph.selectedCell,
cellProperties: []
}
updateSelectedCell() {
if (graph.selectedCell != null) {
this.setState({
selectedCell: graph.selectedCell,
cellProperties: Array.from(graph.selectedCell.value.attributes)
});
}
}
onChangeHandler = (e) => {
console.log(e.target.value);
let cellProperties = [...this.state.cellProperties];
cellProperties[parseInt(e.target.id)] = e.target.value;
this.setState({cellProperties});
}
renderPropertyList() {
return this.state.cellProperties.map((key, i) => {
return <PropertyBarItem name={key.nodeName} value={key.nodeValue} onChange={this.onChangeHandler} key={i} id={i} />
})
}
孩子:
class PropertyBarItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ListItem divider={true} className="property-bar-item">
<TextField
id={this.props.id.toString()}
label={this.props.name}
value={this.props.value}
margin="dense"
onChange={(e) => this.props.onChange(e)}
/>
</ListItem>
)
}
}
当我尝试更改 <TextField> 的 value 时,它会丢失与之配对的原始 label,并且我认为它与父组件状态有任何关系。
然后我收到此错误:组件正在将文本类型的受控输入更改为不受控制。输入元素不应从受控切换到不受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。
我知道这可能是因为我的 cellProperties 状态在开始时是一个空数组,但我的子组件直到数组中有实际值时才会呈现。我对value 字段进行了三元运算,例如value={this.props.value ? this.props.value : ""},但是当我尝试键入时它总是返回一个空字符串。
【问题讨论】:
标签: javascript reactjs