当前,我正在尝试将应用拆分为单独的组件,以使其更具可读性和可测试性。但是现在我遇到了一个问题,那就是父组件中的常规功能。如何从单独的组件调用常规的onChange函数。因为有多个输入字段执行相同的操作,所以我想在父组件中创建一个可重用的函数,可以从子组件中调用该函数。
// child component
export default class Name extends React.Component {
constructor(props) {
super(props);
}
state = {
name: '',
nameErrorMessage: ''
}
checkName = (name: string) => {
const re = /[^a-zA-Z]/;
const checkValidation = re.test(name);
const nameRequirements = !checkValidation && name.length > 1;
if(!nameRequirements) {
this.setState({ nameErrorMessage: 'name contains numbers, symbols or is too short (min length of 2 letters)', nameBoolean: false });
} else {
this.setState({ nameErrorMessage: '', nameBoolean: true });
}
}
handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const getName = event.target.value;
const getNameValid = this.checkName(getName);
return getNameValid;
}
onChange = () => {
this.props.parentMethod();
}
render() {
return (
<div className="two-columns two-columns-child column-block">
<label className="label-customized">First name</label><br/>
<input
name="name"
className="input-customized"
type="text"
value={this.state.name}
onBlur={this.handleNameChange}
onChange={this.onChange}
placeholder="Enter first name"
/>
<br/>
<span className="error-message">{this.state.nameErrorMessage}</span>
</div>
)
}
}
// parent component
onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
let onChangeName:any = event.target.getAttribute('name');
this.setState({[onChangeName]: event.target.value })
}
return (
<div className="App">
<form onSubmit={this.checkForm}>
<Name/>
</form>
</div>
)
答案 0 :(得分:3)
父组件
将onChange
作为属性传递给子组件
...
return (
<div className="App">
<form onSubmit={this.checkForm}>
<Name onChange={this.onChange}/>
</form>
</div>
)
儿童组件
在调用onChange
时调用传递的道具
return <div className="two-columns two-columns-child column-block">
<label className="label-customized">First name</label><br/>
<input
name="name"
className="input-customized"
type="text"
value={this.state.name}
onBlur={this.handleNameChange}
onChange={e => this.props.onChange(e)}
placeholder="Enter first name"
/>
<br/>
<span className="error-message">{this.state.nameErrorMessage}</span>
</div>