我想在material-ui对话框的以下字段中显示required
,最小1
和最大5
验证。目前,我已经添加了一个字段,但是在对话框中单击submit
按钮时,验证的方式未显示出来。有人可以建议我如何解决该问题。
演示链接已添加到此处: https://codesandbox.io/s/tender-wood-3jrwu?file=/src/App.js
const App = () => {
const [rating, setRating] = useState({
ballshooting: "",
dribbling: "",
ballcontrol: "",
sprinting: "",
fitness: ""
});
const [ratingTotal, setRatingTotal] = useState(0);
const [open, setOpen] = React.useState(false);
const { handleSubmit, register, errors } = useForm();
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const onChange = e => {
e.persist();
const ratingValues = {
...rating,
[e.target.name]: e.target.value
};
setRating(ratingValues);
ratingCalculation(ratingValues);
};
const ratingCalculation = ratingValues => {
const {
ballshooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
Number(ballshooting) +
Number(dribbling) +
Number(ballcontrol) +
Number(sprinting) +
Number(fitness);
const finalAvg = newTotal / 5;
setRatingTotal(finalAvg);
return ratingTotal;
};
return (
<form className="ratingForm">
<Button
className="playerRatingBtn"
onClick={() => handleClickOpen()}
variant="outlined"
color="primary"
>
Enter Player Rating
</Button>
<Dialog open={open} onClose={handleClose} aria-labelledby="skills-area">
<DialogTitle id="skills-area">Rate the skills of a player</DialogTitle>
<DialogContent>
<label>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballshooting"
label="Ball Shooting"
type="text"
fullWidth
min={1}
max={5}
ref={register({
required: "Soccer ball shooting skill is required !"
})}
/>
<span className="newsErrorTextFormat">
{errors.shooting && errors.shooting.message}
</span>
</label>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="dribbling"
label="Dribbling"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballcontrol"
label="Ball Control"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="sprinting"
label="Sprinting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="fitness"
label="Fitness"
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button type="submit" onClick={() =>
handleClose(
handleSubmit(calculateAvgRating(ratingCalculation(rating)))
)
} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</form>
);
};
export default App;