在React中,在onchange事件中调用两个函数。

28

我正在尝试使用React中的onChange事件动态调用两个函数以实现搜索功能。在第一个函数中,我正在设置值的状态,而在第二个函数中,我必须调用该值并执行函数。但我无法同时调用这两个函数。本示例代码没有添加模拟JSON数据。

 handleChange(e) {
   this.setState({ value: e.target.value.substr(0, 20) });
}
filterFunction(filteredSections) {
  let search = filteredSections;
  search = filteredSections.filter(somesection => somesection.insidesection && somesection.insidesection.name.toLowerCase().indexOf(this.state.value.toLowerCase()) !== -1);
return search;
    }
 render() {
    const filteredSections = othersection;
return(

<div>
<FormControl
    name="searching"
    placeholder="Searching"
    onChange={e => this.handleChange(e).bind(this)}
    onChange={() => this.filterFunction(filteredSections)}
/>
</div>
<div>
    {filteredSections.map(section =><othersection customization={section} } }
</div>
)
}

预期的是 onchange 事件必须调用两个函数。

2个回答

54

你只能给 onChange 分配一个处理程序。当您使用多个分配时,第二个会覆盖第一个。

您要么需要创建一个调用两个函数的处理程序,要么使用匿名函数:

twoCalls = e => {
  this.functionOne(e)
  this.functionTwo()
}
.
.
.
<FormControl
    name="searching"
    placeholder="Searching"
    onChange={this.twoCalls}
/>

或者...

<FormControl
    name="searching"
    placeholder="Searching"
    onChange={e => { this.functionOne(e); this.functionTwo() }}
/>

1
那个运行得非常好!如果两个函数中的状态需要保持一致,更新它的最佳实践是什么?目前只在第一个函数中更新,在第二个事件发生后的第二个函数中,它显示第一个状态。 - sai
2
状态是异步更新的,因此在第二个函数被调用时它还没有被更新。你可以直接将value传递给第二个函数。 - Herohtar

8
如果您需要道具,可以使用它。
<FormControl
    name="searching"
    placeholder="Searching"
    onChange={e => { this.functionOne(e); this.props.functionTwo(e)}
/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接