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

时间:2016-08-09 14:57:15

标签: javascript user-interface reactjs checkbox web-frontend

我是React的新手,我正在尝试创建一个用户表,并希望使用复选框来管理他们的权限。单击复选框时,我遇到了更新状态的问题。 handleChange方法是我遇到问题的地方。我不知道如何识别正确的复选框以更改该特定用户的状态。我想也许我需要为每个用户添加一个id prop,但这似乎对于大量用户来说可能会失控,即每个用户的每个权限都有一个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']

}

2 个答案:

答案 0 :(得分:2)

首先,您应该为每个用户添加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
      });
    });
  });
}

答案 1 :(得分:0)

查看此库的源代码,了解它们如何管理复选框的状态。也许您甚至可以根据自己的需要使用它:

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