动态填充复选框,并在react redux中维护复选框的状态



我们已经从调用api服务到获取动态填充了复选框项。根据集合,我们将显示状态为checked的复选框。

如果我选中/取消选中复选框,我如何为动态填充的复选框项实现handlechange事件。

我想得到当前的复选框状态。我怎么能拿到

checkboxcontainer.tsx

data.map(item => (
<label key={item.projectId} className="checkBoxcontainer">
<CheckBox   name={item.projectName}  
checked={item.checked} handleChange={this.handleChange} />
{item.projectName}<span className="checkmark"/>
</label>

Redux:

const mapStateToProps=({projects} : ApplicationState) => ({
data: projects.data
});

const mapDispatchToProps = (dispatch: Dispatch) => ({
fetchProjects: bindActionCreators(fetchProjects, dispatch),
});

const ProjectListContainer = connect(mapStateToProps,mapDispatchToProps)(ProjectContainer);
export { ProjectListContainer as ProjectContainer }; 

手柄更换功能:

handleChange(e :any) {
// how to maintain the checkbox state
}

import * as React from 'react';
interface IPropTypes {
type?: string,
name: string,
checked?: boolean,
handleChange(event: any): void;
}
class CheckBox extends React.Component<IPropTypes,{}> {
render() {
return (
<input type='checkbox' name={this.props.name} checked={this.props.checked} 
onChange={ e => this.props.handleChange(e) }   />
);
}
}

我建议传递给Checkbox的handleChange函数如下所示:

handleChange={(e) => this.handleChange(e, item.projectId)} 然后在handleChange中,您可以获取复选框是否被选中,然后用projectId和复选框的状态触发一个操作

const isChecked = event.target.checked; someAction(projectId, isChecked);

此操作应更改redux存储中的数据

最新更新