我有一个文本字段,我需要为其设置一个值,我知道我很可能会为此执行 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>
最佳答案
您必须为 TextField 分配 value 属性:
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>
关于javascript - 使用 react 钩子(Hook)为字段设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56833408/