【发布时间】:2020-01-16 14:07:18
【问题描述】:
我有一个显示简单搜索表单的 React 组件。我正在使用“受控组件”(https://reactjs.org/docs/forms.html),以便 React 组件存储搜索条件并且是事实的来源。
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {criteria: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({criteria: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
// only submit the search if there is search criteria
if (this.state.criteria.length > 0){
// I need to be able to set some state here
this.setState({
.....
});
// i also need to access this.props here
if (this.props......) ...
}
}
render() {
return (
<form onSubmit={this.handleSubmit} >
<input type="text"
placeholder="Search"
value={this.state.criteria}
onChange={this.handleChange} />
<button ...... />
</form>
);
}
}
我想在 2 个地方使用这个 SearchForm。
- 标题中的搜索框:当表单提交时,它会重定向到我的应用程序中的另一个页面
- 搜索页面上的搜索框:当表单提交时,它会更新搜索表单下方的搜索列表
因此,SearchForm 的 onSubmit 方法不能有代码来执行 onForm 提交,因为此代码将根据 SearchForms 的使用情况而有所不同。
我知道如何在我的组件 HTML 中添加搜索表单,例如在 Component1 的渲染方法中我会有
<div>
<SearchForm />
</div>
但是,我不知道如何为使用搜索表单的每个组件以不同的方式处理 SearchForms onSubmit。就像我希望 SearchForm 的 onSubmit 调用包含组件中的方法,传递 SearchForm 的 state.criteria 值
如何在表单提交操作不同的其他组件中重用 SearchForm 组件?
【问题讨论】:
-
只需将附加参数添加到您的组件
<SearchForm onSubmit={yourFunction} />,然后在您的handleSubmit函数中调用它 -
然后像这样在 handleSubmit 中调用你的函数:
this.props.yourFunction()
标签: javascript reactjs forms