javascript - 如何通过子组件的输入字段使用 onChange 更新数组状态
问题描述
我正在尝试更新在我的父组件状态内的数组。每个子组件都是通过父组件状态数组中的一个元素创建的。现在我有一个 onChange 处理程序,它位于我的 Parent 组件中,我将它传递给我的 Child 组件。
以下是一些与此有关的片段:
家长
class PropertyBar extends Component {
state = {
selectedCell: graph.selectedCell,
cellProperties: []
}
onChangeHandler(e) {
let cellProperties = [...this.state.cellProperties];
cellProperties[e.target.name] = e.target.value;
this.setState({cellProperties});
}
renderPropertyList() {
return this.state.cellProperties.map(key => {
return <PropertyBarItem name={key.nodeName} value={key.nodeValue} onChange={this.onChangeHandler}/>
})
}
}
孩子
class PropertyBarItem extends Component {
constructor(props) {
super(props);
}
onChangeHandler(e) {
if (this.props.onChangeHandler) {
this.props.onChangeHandler(e);
}
}
render() {
return (
<ListItem divider={true} className="property-bar-item">
<TextField
id="property"
label={this.props.name}
value={this.props.value}
margin="dense"
onChange={(e) => {this.onChangeHandler(e)}}
/>
</ListItem>
)
}
}
我不认为我onChangeHandler
在 Child 组件中正确处理了传递的内容,但我也可能有逻辑错误。
解决方案
在您的子组件中,您没有onChangeHandler
正确使用该函数,因为您将它作为道具传递,onChange
所以它应该像下面的代码
class PropertyBarItem extends Component {
constructor(props) {
super(props);
this.state = {
input: props.value
}
}
onChange = (event) =>{
this.setState({ input: event.target.value },()=>{ // callback of setState
this.props.onChange(this.state.input) // passing the state to parent component
})
}
render() {
return (
<ListItem divider={true} className="property-bar-item">
<TextField
id="property"
label={this.props.name}
value={this.state.input}
margin="dense"
onChange={this.onChange}
/>
</ListItem>
)
}
}
您还需要onChangeHandle
在父构造函数中绑定或使用箭头函数,如
onChangeHandler = (e) => { // arrow function
console.log(e.target.value) // check
//let cellProperties = [...this.state.cellProperties];
//cellProperties[e.target.name] = e.target.value;
//this.setState({cellProperties});
}
推荐阅读
- javascript - 如何在父级和子级元素上获取父级 ID 单击
- python - Python 哈希不匹配
- sql-server - 我需要使用在一列中具有不同值的触发器批量插入行,例如 1000 行
- c - 销毁双线程二叉树
- python - 查找元组中每个唯一元素的频率(不使用任何列表概念)并与其单词连接
- postgresql - 如何在未将数据从具有流集管道的 CSV 文件插入到 PostgresDB 时解决此问题
- java - 仅在 VSCode 下可以从多个模块问题中访问该包
- angular - 将过滤器选项传递给Angular中的路由
- sql-server - Visual Studio 社区:如何在“SQL Server 对象资源管理器”中查看数据或运行 SQL
- ubuntu-16.04 - 安装 Python 3.7 后遇到 Python 3.5 问题