首页 > 解决方案 > 如何在反应中显示复选框的数量?该功能本身有效,但无法在应用程序中显示计数

问题描述

handleCheckCount 函数外的计数为 0,那么如何在 render 中传递标签中选中框的实际计数?我尝试将状态传递为选中的复选框总数:{this.state.count},但它只返回 0。如果我在 handleCheckCount 函数中使用 console.log(count),它会显示控制台中选中框的数量,但是外面它返回0。

  state={
    checked: false,
    count: 0
  }
  handleCheckCount=()=> {
    let input = document.getElementsByTagName('input');
    let count= this.state.count
    for (var i = 0; i < input.length; i++) {
      if (input[i].type === "checkbox" && input[i].checked === true) {
        count++

      }
    }
    console.log(count)
  }

  render(){
    return(
      <div>
        <table>
        <thead>
        <tr>
          <th className="select_all">
            <input type="checkbox" name="check" id="parent"
              onClick={this.onSelectAll.bind(this)} onChange={this.handleCheckCount}/>
          </th>
          <th>Score</th>
          <th>FirstName</th>
          <th>LastName</th>

        </tr>
        </thead>
      </table>

        <h2>Total Number of Checkbox Selected: </h2>

      </div>
    )
  }

标签: javascriptreactjsjsx

解决方案


这是一个工作示例:

class App extends React.Component {

   state={
    checked: false,
    count: 0
  }

  handleCheckCount=(e)=> {
    // let input = document.getElementsByTagName('input');
    const { checked, type } = e.target;
    // let count= this.state.count
    // for (var i = 0; i < input.length; i++) {
      if (type === "checkbox" && checked === true) {
        this.setState(state => state.count++, this.logCount)
      } else {
        this.setState(state => state.count--, this.logCount)
      }
    // }
  }

  logCount() {
    console.log(this.state.count);
  }

  render(){
    return(
      <div>
        <table>
        <thead>
        <tr>
          <th className="select_all">
            <input type="checkbox" name="check" id="parent" onChange={e => this.handleCheckCount(e)}/>
          </th>
          <th>Score</th>
          <th>FirstName</th>
          <th>LastName</th>

        </tr>
        </thead>
      </table>

        <h2>Total Number of Checkbox Selected: {this.state.count}</h2>

      </div>
    )
  }

}

你的问题是你没有更新你的状态,只是count函数内的作用域变量(你也记录了同一个)。我还添加了一个else块来减少计数,并删除了onClick侦听器。

更新:没有必要使用getElementsbyTagName和 for 循环。您可以使用该事件来获取目标及其属性。

参见 Codepen

希望这可以帮助。


推荐阅读