React中点击Present按钮后如何获取对应学生的姓名?
解决React点击按钮获取对应学生姓名的问题
你需要让present函数能接收到当前点击的学生姓名,有几种简单的实现方式:
方法1:通过箭头函数传递参数
修改present函数,让它接收姓名参数,然后在按钮的onClick事件里用箭头函数把当前学生的姓名传进去:
function present(name){ console.log(name); }
然后更新按钮的点击事件:
<Button onClick={() => present(student.name)}>present</Button>
方法2:使用bind绑定参数
也可以用bind直接绑定参数到函数上:
<Button onClick={present.bind(null, student.name)}>present</Button>
完整修改后的代码
另外注意在列表渲染时要添加唯一的key属性(比如学生的id),避免React警告:
const StudentList = () => { const [studentlist, setStudentList] = useState([]); const studentdataList = async () => { const result = await fetch("http://localhost:5000/api/students"); const studentResult = await result.json(); setStudentList(studentResult); console.log(studentResult[0].name); }; function present(name){ console.log(name); } useEffect(() => { studentdataList(); },[]); return ( <div> {studentlist.map((student) => { return ( <Card style={{ width: "18rem" }} key={student.id}> <Card.Body> <Card.Title> {student.name} </Card.Title> <Button onClick={() => present(student.name)}>present</Button> <Button>abscent</Button> </Card.Body> </Card> ); })} </div> ); }; export default StudentList;
这样点击对应学生的Present按钮时,控制台就会打印出该学生的姓名。
内容的提问来源于stack exchange,提问作者Arijit das
相关产品推荐
相关产品推荐

