reactjs - Checkbox didn't get unchecked once set it to checked in React
问题描述
I am made a dynamic data table in React that gets all its data from a JSON file. One of the table column fields is a 'answered-status' which used to give answer status of the inquiry whether it is answered or not.
I have an 'answered' key with value either answered or unanswered in JSON. When I used that value with my checkbox. I wasn't able to switch back to the original value. Please check below sandbox link for more detail. I use the Bootstrap 4 custom checkbox.
解决方案
首先没有切换复选框的代码
查询列表缺少第二个状态
constructor(props) {
super(props);
this.state = {
searchInquiries: null,
answerStatus: "all",
inquiresList : InquiresList //<--- settting into state for maintaining change
};
}
toggleCheck = (event,inquiry_id) => {
const inquiresList = this.state.inquiresList.map(inquiry => {
return inquiry.id === inquiry_id ? { ...inquiry , "answered" : event.target.checked ? "answered" : "unanswered" } : inquiry
})
this.setState({inquiresList}); //<---- Updating state
};
// There is no need of turnery operator for checked unchecked whole input
<input
type="checkbox"
ref="answerStatus"
checked={inquiry.answered === "answered"} // <---- HERE
onChange={(e) => this.toggleCheck(e,inquiry.id)} // <---- HERE
className="custom-control-input"
id={"answer-status-" + inquiry.id}
name={"answer-status-" + inquiry.id}
/>
工作演示
关于功能的进一步说明inquiresList
:
const inquiresList = this.state.inquiresList.map(inquiry => {
return inquiry.id === inquiry_id ? // checking if inquiry id match
// if matched we need to update that object
{ ...inquiry , "answered" : event.target.checked ? "answered" : "unanswered" } :
// else pass the same object as it is
inquiry // else pass the same object as it is
})
// Why this way?
// because, we don't want to mutate state directly
{
...inquiry , // <-- extract all elements inside inquiry
"answered" : event.target.checked ? "answered" : "unanswered" // <--- We are override the value with it
}
推荐阅读
- webpack - webpack将数字编译为json文件中的哈希字符串,该文件具有许多浮点数
- java - SpringBoot web socket服务器没有响应
- laravel - Github Actions,我遇到这样的错误 Error: Process completed with exit code 1
- flutter - 错误无法将参数类型“PdfImage”分配给参数类型“ImageProvider”
- r - 按模式重命名列名
- encryption - 什么命令会增加系统的安全级别?
- c++ - C ++我如何在一个类中循环函数,以便我可以设置多个学生信息?
- android - 如何使用 WebAuthenticator 为 Android 提供私有身份验证会话以进行 Google 身份验证
- php - PHP致命错误:未捕获的错误:调用未定义的函数
- windows - 如何确定 Windows 从哪个驱动器启动?