复选框默认检查状态问题

问题描述 投票:1回答:1

我有以下代码。在我的项目中,我现在正面临一些问题。我想在getElements()而不是map()中使用forEach()循环,并且我想在检查复选框后立即显示默认检查,然后再返回那里。

有什么帮助这个问题?

这是=> DEMO

import React, { Component } from 'react';
import { render } from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Checkbox from 'material-ui/Checkbox';

class App extends Component {
   itemsPerPage = 4
   constructor(props) {
      super(props);
      var ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
      this.state = {
      ids: ids,
      idsChecked: ids.map(() => false),
      page: 0
   }
  }
  componentDidMount = () => {
  }
  handlePrevious = () => {
     this.setState({ page: this.state.page - 1 });
  }
  handleNext = () => {
     this.setState({ page: this.state.page + 1 });
  }
  handleCheck = (e) => {
    var id = Number(e.currentTarget.id);
    var idsChecked = this.state.idsChecked.map((bool, i) => i === id ? !bool : bool);
    this.setState({ idsChecked: idsChecked });
  }
  handleDetails = (e) => {
    var id = Number(e.currentTarget.getAttribute("rel"));
    console.log("even or odd is clicked! (button #id: " + id + ")");
  }
  getElements = () => {
    var first = this.state.page * this.itemsPerPage;
    var trs = this.state.ids.slice(first, first + this.itemsPerPage).map((element, i) => {
    let details = <button rel={first + i} onClick={this.handleDetails}> {element % 2 ? "odd" : "even"} </button>;
     return (
      <tr key={element}>
         <td><Checkbox
               checked={this.state.idsChecked[first + i]}
               id={first + i}
               onCheck={this.handleCheck}
         /></td>
         <td>{element}</td>
         <td>{details}</td>
      </tr>
    );
  });
  return trs;
}
render() {
   var hasPrevious = this.state.page > 0;
   var hasNext = this.state.page < Math.floor((this.state.ids.length - 1) / this.itemsPerPage);
   var tdStyle = {width: "80px"}
   return (
     <div>
       <div>
         <table>
            <tbody>
              <tr>
                <td style={tdStyle}>{hasPrevious && <button onClick={this.handlePrevious} hidden={this.state.hasPrevious}> Previous </button>}</td>
                <td style={tdStyle}>{hasNext && <button onClick={this.handleNext} hidden={this.state.isNext}> Next </button>}</td>
             </tr>
           </tbody>
         </table>
       </div>
       <div>
         <table>
           <tbody>
             {this.getElements()}
           </tbody>
         </table>
       </div>
      </div>
  );
 }
}

render(<MuiThemeProvider><App /></MuiThemeProvider>, document.getElementById('root'));
javascript reactjs checkbox components material-ui
1个回答
1
投票
  1. 要用qazxsw poi替换qazxsw poi,将复选框元素推入数组,并从map返回该数组。
  2. 使用forEach组件的getElements()将默认值设置为true。

完整代码:

defaultChecked props
© www.soinside.com 2019 - 2024. All rights reserved.