如何从React中的高阶组件重置表单?
问题描述:
Iam在react.js中做了一个应用程序,其中iam将组件传递给更高级的组件。现在在表单提交PersonalInformation
组件后,表单需要重置哪些不会发生。这不是由refs发生的。如何从React中的高阶组件重置表单?
class PersonalInformation extends Component{
render(){
return(
<div>
<h3>Personal Information</h3>
<Form onSubmit={this.props.handleSubmit} ref="form" name="form">
<fieldset disabled={this.props.disabled}>
<Input type="text" name="firstName" title="FirstName" value=""/><br/>
<Input type="text" name="lastName" title="LastName" value=""/><br/>
<Input type="text" name="fatherName" title="Fathers's Name" value=""/><br/>
<Input type="text" name="motherName" title="Mother's Name" value=""/><br/>
</fieldset>
<button className="btn btn-default">{this.props.buttonName}</button>
</Form>
</div>
)
}
}
现在高阶组件是:
var MyHoc = function(AbstractComponent){
return class extends React.Component {
constructor(props){
super(props);
this.state={
buttonName:'Edit',
disabled:true,
anotherForm:false
}
this.handleSubmit=this.handleSubmit.bind(this);
this.newForm=this.newForm.bind(this);
}
handleSubmit(data){
this.setState({
buttonName:'Save',
disabled:false
})
if(!this.state.disabled){
console.log(data);
this.refs.form.reset();
}
}
newForm(){
this.setState({
anotherForm:true
})
}
render() {
return <AbstractComponent {...this.state} handleSubmit={this.handleSubmit}
newForm={this.newForm} />;
}
}
}
export default MyHoc(PersonalInformation);
答
您无法从不同的组件访问参考。 this.refs引用在该特定组件中定义的ref。
您可以在handleSubmit函数中传递回调方法,并且handlesubmit在它要重置表单时调用该方法。事情是这样的
handleSubmit(data, resetFormCallback){
this.setState({
buttonName:'Save',
disabled:false
})
if(!this.state.disabled){
console.log(data);
resetFormCallback();
}
}
,然后在子组件您传递一个回调方法,同时呼吁handleSubmit
class PersonalInformation extends Component{
resetForm =() => {
this.refs.form.reset();
}
render(){
return(
<div>
<h3>Personal Information</h3>
<Form onSubmit={(data) => {this.props.handleSubmit(data, this.resetForm)}} ref="form" name="form">
<fieldset disabled={this.props.disabled}>
<Input type="text" name="firstName" title="FirstName" value=""/><br/>
<Input type="text" name="lastName" title="LastName" value=""/><br/>
<Input type="text" name="fatherName" title="Fathers's Name" value=""/><br/>
<Input type="text" name="motherName" title="Mother's Name" value=""/><br/>
</fieldset>
<button className="btn btn-default">{this.props.buttonName}</button>
</Form>
</div>
)
}
}
答
this
是指在手的组件。你正在寻找另一个组件的参考,所以这是行不通的。
在这一行:this.refs.form.reset();
改为设置一些状态,如resetForm:true
,然后传递给您的子组件。然后,您可以根据通过道具传递给它的状态来重置表单。