如何使用 React 从 Dialog 中的 material-ui TextFileds 获取值?
How do I get values from material-ui TextFileds in Dialog with React?
所以我有以下对话框:
<Dialog>
<DialogContent sx={{ display: "flex", flexDirection: "column" }}>
<TextField
id="item-name"
label="Item Name"
/>
<TextField
id="item-description"
label="Item Description"
multiline
/>
</DialogContent>
<DialogActions>
<Button onClick={onAddDialogClose}>Cancel</Button>
<Button onClick={onAddNewItem}>Add Item</Button>
</DialogActions>
</Dialog>
我想使用单击“添加项目”按钮时那些字段中的数据进行 REST API 调用。我如何从 <TextField>
s 中获取这些值?
您应该通过向它们添加状态来制作您的 TextFields controlled component
:
const [itemName, setItemName] = useState('')
const [itemDest, setItemDest] = useState('')
const onAddNewItem = () => {
api.call(itemName, itemDest) // or whatever you want
console.log(itemName)
console.log(itemDest)
setItemName('')
setItemDest('')
}
return (
<Dialog>
<DialogContent sx={{ display: 'flex', flexDirection: 'column' }}>
<TextField
id="item-name"
label="Item Name"
value={itemName}
onChange={e => {
setItemName(e.target.value)
}}
/>
<TextField
id="item-description"
label="Item Description"
multiline
value={itemDest}
onChange={e => {
setItemDest(e.target.value)
}}
/>
</DialogContent>
<DialogActions>
<Button onClick={onAddDialogClose}>Cancel</Button>
<Button onClick={onAddNewItem}>Add Item</Button>
</DialogActions>
</Dialog>
)
所以我有以下对话框:
<Dialog>
<DialogContent sx={{ display: "flex", flexDirection: "column" }}>
<TextField
id="item-name"
label="Item Name"
/>
<TextField
id="item-description"
label="Item Description"
multiline
/>
</DialogContent>
<DialogActions>
<Button onClick={onAddDialogClose}>Cancel</Button>
<Button onClick={onAddNewItem}>Add Item</Button>
</DialogActions>
</Dialog>
我想使用单击“添加项目”按钮时那些字段中的数据进行 REST API 调用。我如何从 <TextField>
s 中获取这些值?
您应该通过向它们添加状态来制作您的 TextFields controlled component
:
const [itemName, setItemName] = useState('')
const [itemDest, setItemDest] = useState('')
const onAddNewItem = () => {
api.call(itemName, itemDest) // or whatever you want
console.log(itemName)
console.log(itemDest)
setItemName('')
setItemDest('')
}
return (
<Dialog>
<DialogContent sx={{ display: 'flex', flexDirection: 'column' }}>
<TextField
id="item-name"
label="Item Name"
value={itemName}
onChange={e => {
setItemName(e.target.value)
}}
/>
<TextField
id="item-description"
label="Item Description"
multiline
value={itemDest}
onChange={e => {
setItemDest(e.target.value)
}}
/>
</DialogContent>
<DialogActions>
<Button onClick={onAddDialogClose}>Cancel</Button>
<Button onClick={onAddNewItem}>Add Item</Button>
</DialogActions>
</Dialog>
)