我想做什么:
我正在尝试将子组件中的字符串传递给父组件的handleChange函数。
目前可行的方法:
我有一个父React JS类,其中包含以下方法:
handleChange(event) {
console.log(event.target.value);
}
在渲染函数中,我有以下代码:
<Child handleChange={this.handleChange.bind(this)} />
在Child类中,我有:
<fieldset onChange={this.props.handleChange}>
<div>Tag 1: <input id="tag1" value={tags[0]} /></div>
<div>Tag 2: <input id="tag2" value={tags[1]} /></div>
<div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
这个很好用。
我想要做的事情:
我试图向handleChange函数添加一个 section
参数,如下所示:
handleChange(section, event) {
console.log(section);
console.log(event.target.value);
}
而在Child类中,我有:
<fieldset onChange={this.props.handleChange("tags")}>
<div>Tag 1: <input id="tag1" value={tags[0]} /></div>
<div>Tag 2: <input id="tag2" value={tags[1]} /></div>
<div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>
现在我遇到了错误:
Uncaught TypeError: Cannot read property 'target' of undefined
第二个 console.log 语句中出现了这个错误。
我做错了什么?
此外,我正在考虑使 section
参数变为可选。如果是这样,有没有简单的方法可以实现?如果事件参数需要放在最后的话,似乎可能不可行。