【发布时间】:2019-06-14 13:38:39
【问题描述】:
我有一个包含这些数据的常量文件:
export let testing= [
{ id: 'test1', label: 'Test1' },
{ id: 'test2', label: 'Test2' },
{ id: 'test3', label: 'Test3' }
]
在我的 checkboxes.js 中,
class CheckBoxes extends Component {
constructor(props) {
super(props);
this.state = ({
checkBoxArray: [],
isChecked: false
})
}
handleSubmit = (event) => {
event.preventDefault(); //use for testing only
fetch(`${process.env.REACT_APP_SERVER_URL}/testing`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
check_box_data: event.target.check_box_name[].value, //error
})
})
.then(response => {
console.log(response);
if (response.status === 200) {
console.log('Success')
} else {
alert('Failed')
}
})
.catch(error => {
alert('Server error')
});
}
handleCheckBoxChange = (index) => { //not working
const {checkBoxArray} = this.state;
checkBoxArray[index].checked = !checkBoxArray[index].checked;
this.setState({ //this line causes maximum depth mount error
checkBoxArray
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<div>
{
this.state.checkBoxArray.map((object, index) => {
return (
<CheckBoxComponent
key={index}
check_box_id={object.id}
check_box_name='check_box_name[]'
check_box_label={object.label}
check_box_value={object.id}
isChecked={this.state.isChecked}
handleCheckBoxChange={this.handleCheckBoxChange(index)}
/>
);
})
}
<SingleButtonComponent button_type='submit' button_value='Create Now' />
</div>
</form>
</div>
)
}
}
export default CheckBoxes;
在我的复选框组件js中:
import React from 'react';
const CheckBoxComponent = (props) => {
const { check_box_id, check_box_name, check_box_label, check_box_value, isChecked, handleCheckBoxChange } = props;
return (
<div>
<input type='checkbox' id={check_box_id} name={check_box_name} value={check_box_value} checked={isChecked} onChange={handleCheckBoxChange}/>
<label htmlFor={check_box_id} className='lh-copy'> {check_box_label}</label>
</div>
)
}
export default CheckBoxComponent;
我的第一个问题是我无法将复选框值作为数组发布到 fetch api 中。显然[] 不允许在event.target.check_box_name[].value 中使用。我尝试做event.target.check_box_name.value,但它返回无法读取未定义的属性“值”。我想将复选框值的数组发送回服务器。
我的第二个问题是我不知道如何设置动态生成的复选框。这段代码将检查所有复选框。我在常量文件中只显示了 3 行数据,而且还不止这些,所以我不会接受任何静态工作的解决方案。
【问题讨论】:
-
对于动态复选框实现(没有异步部分),请查看此答案:stackoverflow.com/questions/53189290/…
标签: reactjs post checkbox event-handling fetch