[英]How to get the value of the checkbox lable in material-ui?
I am using Checkbox from material ui.我正在使用材料 ui 中的复选框。 This is the import statement:
这是导入语句:
import Checkbox from '@mui/material/Checkbox';
I have the following code being rendered:我正在呈现以下代码:
<Checkbox value="Tutor 1" onClick={() => handleSendSelection()}/>
I want to get the value of the selected checkbox inside the handleSendSelection() function.我想在 handleSendSelection() function 中获取选中复选框的值。 When I print the value, it gives me undefined, whereas my expected value is the string "Tutor 1".
当我打印该值时,它给了我未定义的值,而我的预期值是字符串“Tutor 1”。 How should I get the value of the checkbox?
我应该如何获得复选框的值?
const handleSendSelection = (event) => { console.log("value - ", event.target.value); }
import { useState } from "react";
import "./styles.css";
export default function App() {
const [value, setValue] = useState("")
return (
<div className="App">
<input type="checkbox" value={value} onChange={() => (setValue("tutor_1"))} />
</div>
);
}
You can do something like that try to make an controlled checkbox qand set it according to your choice您可以执行类似的操作,尝试制作一个受控复选框 q 并根据您的选择进行设置
You did not pass the event in onclick function.您没有通过 onclick function 中的事件。
<Checkbox value="Tutor 1" onClick={(event) => handleSendSelection(event)}/>
const handleSendSelection = (event) => {
console.log("value - ", event.target.value);
}
Here's the working sandbox code https://codesandbox.io/s/checkboxes-material-demo-forked-4xo59?file=/demo.js这是工作沙箱代码https://codesandbox.io/s/checkboxes-material-demo-forked-4xo59?file=/demo.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.