我有一个文本字段,我需要为其设置一个值,我知道我很可能为此做一个handleChange
,但是我正在使用reactHooks
(useState),但我没有确保在用户输入时如何保留该值。
const handleChange = () => {
//something
}
const [comment, setComment] = useState();
<Grid item xs={12} sm={6}>
<TextField
className={classes.field}
id="comments"
name="comments"
label="Comments"
fullWidth
onChange={handleChange}
autoComplete="lname"
inputProps={{
maxLength: 250
}}
/>
</Grid>
答案 0 :(得分:1)
您必须将value属性分配给TextField:
const [comment, setComment] = useState(''); // '' stands for initial value - empty string
const handleChange = (e) => {
setComment(e.target.value);
}
<Grid item xs={12} sm={6}>
<TextField
value={comment} // here you assign the comment as TextField's value
className={classes.field}
id="comments"
name="comments"
label="Comments"
fullWidth
onChange={handleChange}
autoComplete="lname"
inputProps={{
maxLength: 250
}}
/>
</Grid>