我正在构建一个页面来创建帖子,用户可以在其中选择多个类别,
当我用post请求发送带有多个类别对象的数据时,我遇到了问题,无法在单个对象中收集多个类别I,以便与其他数据一起发送。
默认状态
constructor (props){
super(props);
this.state = {
title: '',
menuItems: [],
shortDescription: '',
body: RichTextEditor.createEmptyValue(),
metaDescription: ''
};
this.onChangeHandler = this.onChangeHandler.bind(this);
}关于其他字段的更改处理程序的()
onChangeHandler = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name] : value
})
}类别更改处理程序,它返回每个类别id的新数组对象。
categoryChangeHandler = (e, data) => {
let selectedMenuItems = {
categoryId: data.value,
}
console.log(selectedMenuItems);
}从api获取类别列表
{this.state.menuItems.map((menuItem) =>
<Grid.Column key={menuItem.id} width={4}>
<Checkbox label={menuItem.title} name={menuItem.title}
key={menuItem.id}
value={menuItem.id}
onChange={(e, data) => this.categoryChangeHandler(menuItem.key, data)} />
</Grid.Column>
)}发布于 2018-10-13 12:58:26
您可以编写一个单独的复选框更改处理程序,将所有复选框值存储在状态下的一个JSON对象中。
handleCheckBoxChange(e) {
const tempState = {
checkboxValues: {
...this.state.checkboxValues,
[e.target.name]: e.target.checked
}
}
this.setState(tempState)
}发布于 2018-10-14 09:53:32
您需要在状态中添加一个新属性来收集复选框数据,例如selectedMenuItems:
constructor (props){
super(props);
this.state = {
title: '',
menuItems: [],
shortDescription: '',
selectedMenuItems: [], //new property
body: RichTextEditor.createEmptyValue(),
metaDescription: ''
};
this.onChangeHandler = this.onChangeHandler.bind(this); //you don't need this line as you are using and arrow function
}然后在更改处理程序中进行以下更改:
categoryChangeHandler = (e) => {
const name = e.target.name;
let selectedMenu = this.state.selectedMenuItems;
selectedMenu[name] = e.target.checked;
this.setState({
selectedMenuItems : selectedMenu
});
}然后像这样调用这个处理程序:
{this.state.menuItems.map((menuItem) =>
<Grid.Column key={menuItem.id} width={4}>
<Checkbox label={menuItem.title} name={menuItem.title}
key={menuItem.id}
value={menuItem.id}
onChange={this.categoryChangeHandler} />
</Grid.Column>
)}建议不要在呈现函数中直接使用箭头函数,因为它每次呈现组件时都会创建一个新函数。这可能会导致性能问题。
https://stackoverflow.com/questions/52791471
复制相似问题