反应多个onChange和返回值



我试图在文本字段中设置最大输入值,但似乎无法使其工作。

我有2个onChange和值,我认为这是问题所在。不知道该怎么做

function Form({ onAddStudent }) {
const [open, setOpen] = React.useState(false);
const [number, setNumber] = React.useState(null);
const handleClose = () => setOpen(false);
const [maxnumber, setMaxNumber] = useState("");
const handler = (event) => {
const maxvalue = event.target.value;
const setMaxValue = maxvalue <= 10 ? maxvalue : maxnumber;
setMaxNumber(setSetValue);
};
const handleAdd = () => {
onAddStudent(number);
handleClose();
};

然后我有一个返回语句它有两个onchanges和值

return (
<div>
<Button variant="contained" size ="small" fontSize="large" onClick={() => setOpen(true)}>
</Button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Number of Students</DialogTitle>
<DialogContent>
<DialogContentText>Students to Add:</DialogContentText>
<TextField   
onChange={(e) => {setNumber(e.target.value)}}
value={number}
onChange={handler}
value={maxvalue}
/>
</DialogContent>
<DialogActions>
<Button 
onClick={handleClose}>Cancel</Button>
<Button onClick={handleAdd}>Add</Button>
</DialogActions>
</Dialog>
</div>
);
}

可以像这样合并两个处理程序:

<TextField
onChange={(e) => {
setNumber(e.target.value);
handler(e);
}}
value={number}
onChange={handler}
value={maxvalue}
/>

如果你运行这段代码:

<TextField
onChange={(e) => {setNumber(e.target.value)}}
onChange={handler}

那么下面的onChange道具将覆盖上面的

function Form({ onAddStudent }) {
const [open, setOpen] = useState(false);
const handleClose = () => setOpen(false);
const [maxnumber, setMaxNumber] = useState("");
const handler = (event) => {
const maxvalue = event.target.value;
setMaxNumber((prev) => {
// only allow 11 characters
return maxvalue.substring(0, 11);
});
};
const handleAdd = () => {
onAddStudent(maxnumber);
handleClose();
};
return (
<div>
<Button
variant="contained"
size="small"
fontSize="large"
onClick={() => setOpen(true)}
>
Open
</Button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Number of Students</DialogTitle>
<DialogContent>
<DialogContentText>Students to Add:</DialogContentText>
<TextField onChange={handler} value={maxnumber} />
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleAdd}>Add</Button>
</DialogActions>
</Dialog>
</div>
);
}

您也可以在CodeSandbox中与我的演示交互

编辑:

删除:

- const string = prev.length <= 10 ? maxvalue : maxvalue.substring(0, 10);
- return string;

添加:

+ return maxvalue.substring(0, 11);

相关内容

  • 没有找到相关文章

最新更新