我编写了一个自定义Input
类组件。
class Input extends React.Component {
validate = () => {
// validation logic
}
handleChange = () => {this.validate()}
render () {
return <input onChange={this.handleChange} name={this.props.name} type={this.props.type}/>
}
}
在 Form
组件中,我像这样使用它。
class Form extends React.Component {
handleSubmit () => {
// trigger Input validation here
}
render () {
return <form onSubmit={this.handleSubmit}>
<Input name="abc" type=""/>
<Input name="abc" type="password"/>
</form>
}
}
Form
组件中可以嵌套超过 20 个 Input
组件。我的问题是,当提交表单时,如何从父 Form
组件触发输入组件的验证?由于我有很多输入组件,我需要一种方法来调用每个输入实例的所有验证方法。
最佳答案
父组件应该有子组件的引用才能访问其方法:
refs = {
foo: React.createRef(),
bar: React.createRef()
}
handleSubmit () => {
for (const [refName, ref] of Object.entries(this.refs)) {
const isValid = ref.current.handleSubmit();
// ...
}
}
render () {
return <form onSubmit={this.handleSubmit}>
<Input ref={this.refs.foo} name="foo"/>
<Input ref={this.refs.bar} name="bar"/>
</form>
}
如果有很多输入,可以通过自动注册具有与 name
属性匹配的相应名称的引用来使代码更加干燥。
关于javascript - react JS : How to call a validation method of a custom Input component from its Parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54378473/