如何在React中使用复选框管理状态



我是React的新手,我正在尝试制作用户表,并希望使用复选框来管理他们的权限。当我单击复选框时,我遇到了更新状态的问题。handleChange方法是我遇到问题的地方。我不知道如何确定正确的复选框来更改特定用户的状态。我想也许我需要添加一个id道具到每个,但这似乎可能会失控的大量用户,即一个id为每个用户的每个权限。我觉得这应该不难,但我已经被困了很长时间了。

我的组件代码如下。

import React from 'react'
import {Link} from 'react-router'
import {Panel, Button, PageHeader, Row, Col, Table, Input} from 'react-bootstrap'

export class UserPermissions extends React.Component {
constructor() {
    super();
    this.state = {
        users: [
            {   
                name: 'Jerry',
                viewAccounts: true,
                modifyAccounts: true,
                viewUsers: false,
                modifyUsers: true
            },
            {   
                name: 'George',
                viewAccounts: false,
                modifyAccounts: true,
                viewUsers: false,
                modifyUsers: false
            },
            {   
                name: 'Elaine',
                viewAccounts: true,
                modifyAccounts: false,
                viewUsers: false,
                modifyUsers: true
            }
    ]
    }               
}   
handleChange(e){
  //not sure how to write this
}
renderHeadings(data){
    return data.map((step, index) => <th key={index} style={{align:"center"}}>{step}</th>);
}
renderRows(data){
    return data.map((step, index) => 
            <tr key={index}>
                <td>{step['name']}</td>
                <td style={{align:"center", paddingLeft:"40px"}}>
                    <Input type="checkbox"
                           checked={step['viewAccounts']} 
                           onChange={this.handleChange}/></td>
                <td style={{align:"center", paddingLeft:"40px"}}>
                    <Input type="checkbox"
                           checked={step['modifyAccounts']} 
                           onChange={this.handleChange}/></td>
                <td style={{align:"center", paddingLeft:"40px"}}>
                    <Input type="checkbox"
                           checked={step['viewUsers']} 
                           onChange={this.handleChange}/></td>
                <td style={{align:"center", paddingLeft:"40px"}}>
                    <Input type="checkbox"
                           checked={step['modifyUsers']}
                           onChange={this.handleChange} /></td>
                <td style={{align:"center"}}>
                    <Link to="/users"><i className="fa fa-edit fa-2x fa-fw" /></Link>
                    <Link to="/users"><i className="fa fa-times-circle fa-2x fa-fw" /></Link></td>
            </tr>
    );
}
render() {
    return (
        <div>
             <Row>
                <Col lg={12}>
                    <PageHeader>User Permissions</PageHeader>
                </Col>
                <Col lg={12}>
                    <Panel header={<span>Users</span>} bsStyle="primary">
                        <div>
                            <div className="dataTable_wrapper">
                                <div id="dataTables-example_wrapper" className="dataTables_wrapper form-inline dt-bootstrap no-footer">
                                    <Row>
                                        <Col sm={12}>
                                            <Table striped condensed responsive>
                                                <thead>
                                                <tr>
                                                    {this.renderHeadings(this.props.headings)}
                                                </tr>
                                                </thead>
                                                <tbody>
                                                    {this.renderRows(this.state.users)}
                                                </tbody>
                                            </Table>
                                        </Col>
                                    </Row>
                                </div>
                            </div>
                        </div>
                    </Panel>
                    <Button bsStyle="success">Add User</Button>
                </Col>
            </Row>
        </div>
        );
}
}
UserPermissions.propTypes = {
headings: React.PropTypes.array
}
UserPermissions.defaultProps = {
headings: ['Name', 'View Accounts', 'Modify Accounts', 'View Users', 'Modify Users']
}

首先,您应该向每个用户添加id。按用户名标识用户是一个不好的做法:

constructor() {
  super();
  this.state = {
    users: [
      {   
        id: 1,
        name: 'Jerry',
        viewAccounts: true,
        modifyAccounts: true,
        viewUsers: false,
        modifyUsers: true
      },
      { 
        id: 2,  
        name: 'George',
        viewAccounts: false,
        modifyAccounts: true,
        viewUsers: false,
        modifyUsers: false
      },
      {   
        id: 2,
        name: 'Elaine',
        viewAccounts: true,
        modifyAccounts: false,
        viewUsers: false,
        modifyUsers: true
      }
    ]
  }               
}

接下来,你应该给this.handleChange函数提供用户的id,我们要改变的属性的name,以及当前的value:

renderRows(data) {
  return data.map((step, index) => 
    <tr key={index}>
      <td>{step['name']}</td>
      <td style={{align:"center", paddingLeft:"40px"}}>
        <Input type="checkbox"
          checked={step['viewAccounts']} 
          onChange={e => this.handleChange(step.id, 'viewAccounts', step['viewAccounts'])}/></td>
      <td style={{align:"center", paddingLeft:"40px"}}>
        <Input type="checkbox"
          checked={step['modifyAccounts']} 
          onChange={e => this.handleChange(step.id, 'modifyAccounts', step['modifyAccounts'])}/></td>
      <td style={{align:"center", paddingLeft:"40px"}}>
        <Input type="checkbox"
          checked={step['viewUsers']} 
          onChange={e => this.handleChange(step.id, 'viewUsers', step['viewUsers'])}/></td>
      <td style={{align:"center", paddingLeft:"40px"}}>
        <Input type="checkbox"
          checked={step['modifyUsers']}
          onChange={e => this.handleChange(step.id, 'modifyUsers', step['modifyUsers'])}/></td>
      <td style={{align:"center"}}>
        <Link to="/users"><i className="fa fa-edit fa-2x fa-fw" /></Link>
        <Link to="/users"><i className="fa fa-times-circle fa-2x fa-fw" /></Link></td>
    </tr>
  );
}

最后,在this.handleChange函数中,我们应该根据给定的值更新特定的用户数据:

handleChange(id, name, value) {
  this.setState({
    users: this.state.users.map((user) => {
      if (user.id !== id) return user;
      // `Object.assign` function is used to return new modified object.
      return Object.assign({}, user, {
        // We should assign opposite to `value` variable value, as we are toggling permissions.
        [name]: !value
      });
    });
  });
}

查看这个库的源代码,了解它们如何管理复选框的状态。也许你甚至可以用它来满足你的需要:

https://www.npmjs.com/package/react-checkbox-group

相关内容

  • 没有找到相关文章

最新更新