代码之家  ›  专栏  ›  技术社区  ›  James Thibaudeau

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

  •  0
  • James Thibaudeau  · 技术社区  · 10 年前

    我是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']
    
    }
    
    2 回复  |  直到 10 年前
        1
  •  2
  •   1ven    10 年前

    首先,您应该添加 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 作用 身份证件 用户的, 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.handle更改 函数,我们应该根据给定的值更新特定的用户数据:

    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
          });
        });
      });
    }
    
        2
  •  0
  •   ziad-saab    10 年前

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

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