面试题答案
一键面试实现思路
- 创建高阶组件:接收一个组件作为参数,返回一个新的增强组件。
- 添加校验逻辑:在高阶组件中,获取表单输入数据,针对邮箱格式等进行校验。
- 传递校验结果:将校验结果通过props传递给被包裹组件,以便进行相应处理。
代码示例
import React from 'react';
// 邮箱格式校验函数
const validateEmail = (email) => {
const re = /\S+@\S+\.\S+/;
return re.test(email);
};
// 高阶组件
const withFormValidation = (WrappedComponent) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
emailError: ''
};
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleEmailChange(e) {
const email = e.target.value;
if (!validateEmail(email)) {
this.setState({
emailError: '邮箱格式不正确'
});
} else {
this.setState({
emailError: ''
});
}
this.setState({
email
});
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.emailError) {
// 可以在这里进行提交表单等操作
console.log('表单数据合法,可提交');
}
}
render() {
const { email, emailError } = this.state;
return (
<WrappedComponent
email={email}
emailError={emailError}
handleEmailChange={this.handleEmailChange}
handleSubmit={this.handleSubmit}
{...this.props}
/>
);
}
};
};
// 被包裹的表单组件
const FormComponent = ({ email, emailError, handleEmailChange, handleSubmit }) => {
return (
<form onSubmit={handleSubmit}>
<label>邮箱:</label>
<input
type="text"
value={email}
onChange={handleEmailChange}
/>
{emailError && <span style={{ color:'red' }}>{emailError}</span>}
<button type="submit">提交</button>
</form>
);
};
// 使用高阶组件增强表单组件
const EnhancedForm = withFormValidation(FormComponent);
export default EnhancedForm;
在上述代码中,withFormValidation
高阶组件增强了 FormComponent
,为其添加了邮箱格式校验功能。FormComponent
可以通过props获取校验状态和处理函数,从而实现对用户输入的实时校验和反馈。