我需要添加验证名称字段在reactjs功能组件,但不知道为什么它不工作?我刚刚添加了验证表单firstname,并单击提交按钮,我需要显示验证,如果firstname未定义。我的代码有什么问题?
const [state, setState] = React.useState({
data: {
firstName: 'milan',
lastName: 'sai',
number: '999,
},
firstNameValid: '',
lastNameValid: '',
numberValid: '',
});
const handleTextareaChange = (event) => {
const { data } = state;
data[event.target.name] = event.target.value;
setState({
data,
});
};
const valid = () => {
if (state.data.firstName === 'undefined') {
setState({ firstNameValid: 'Required.Please enter your given name.' });
}
};
return (
<div>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing4x} />
<h1 tabIndex="-1" className="HeadingB mt-sheet-heading">
{CMS.heading1}
</h1>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing3x} />
<TextField id="givenName" name="firstName" label={CMS.name} onChange={handleTextareaChange} value={state.data.firstName} />
<p>{state.firstNameValid}</p>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing3x} />
<TextField id="familyName" name="lastName" label={CMS.familyName} onChange={handleTextareaChange} value={state.data.lastName} />
<p>{state.lastNameValid}</p>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing3x} />
<TextField id="mobileNumber" name="number" label={CMS.mobile} onChange={handleTextareaChange} value={state.data.number} />
<p>{state.numberValid}</p>
<VerticalSpacing size={ABLE_SPACING_SIZE.spacing4x} />
<ActionButton className={styles.saveCta} variant="HighEmphasis" label={CMS.saveCTA} onClick={() => valid()} />
</div>
);
您不应该使用引号(如'undefined'
)检查给定值是否为undefined
。修改这一行
const valid = () => {
if (state.data.firstName === 'undefined') {
setState({ firstNameValid: 'Required.Please enter your given name.' });
}
};
const valid = () => {
if (!state.data.firstName) {
setState({
...state,
firstNameValid: "Required.Please enter your given name."
});
} else {
setState({
...state,
firstNameValid: ""
});
}
};
你可以看看这个沙箱的实际工作示例。