我有2个输入(名字,姓氏),并且想绑定单个模糊事件。如何处理呢?
class SimpleForm extends React.Component {
state = {
firstName: "",
firstNameError: "",
lastName: "",
lastNameError: ""
};
validateName = name => {
const regex = /[A-Za-z]{3,}/;
return !regex.test(name)
? "The name must contain at least three letters. Numbers and special characters are not allowed."
: "";
};
onLastNameBlur = () => {
const { lastName } = this.state;
const lastNameError = this.validateName( lastName) ;
return this.setState({ lastNameError });
};
onFirstNameBlur = () => {
const { firstName } = this.state;
const firstNameError = this.validateName( firstName );
return this.setState({ firstNameError });
};
onNameChange = e =>
this.setState({[e.target.name]: e.target.value});
render() {
const { firstNameError, firstName, lastName, lastNameError } = this.state;
return (
<div style={style.form}>
<TextField name="firstName"
label="First name:"
onChange={this.onNameChange}
onBlur={this.onFirstNameBlur}
error={firstNameError} />
<TextField name="lastName"
label="Last name:"
onChange={this.onNameChange}
onBlur={this.onLastNameBlur}
error={lastNameError} />
<Greetings firstName={firstName} lastName={lastName} />
</div>
);
}
}
export default SimpleForm;
如果看到的话,我们的onLastNameBlur和onFirstNameBlur具有类似的代码。我来自https://github.com/suzdalnitski/medium-intro-react
的示例答案 0 :(得分:2)
像onNameChange一样,您可以使用e.target.name
知道当前输入;