javascript - React JS 中的复选框绑定(bind)

标签 javascript reactjs react-native checkbox

我正在尝试使用 reactJS 创建一个简单的复选框,并尝试使用 handlecheck() 绑定(bind)复选框的状态

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    <title>Getting Started with React</title>
</head>
<body>
  <div id='react-container'></div>
  <script type="text/babel">
    
    class Checkbox extends React.Component{
      constructor(props){
        super(props)
        this.state = {
          checked: false
        }
        this.handleCheck = this.handleCheck.bind(this)
      }

      handleCheck(){
        this.setState ({
          checked: true
        })
      }

      render(){
        return(
          <div>
            <input type = "checkbox"/>
          </div>
        )
      }
    }

    ReactDOM.render(
      <Checkbox />,
      document.getElementById("react-container")
    )
  </script>

</body>
</html>

但是,这里虽然我在用

handleCheck(){
                this.setState ({
                  checked: true
                })
              } 

我仍然可以多次选中和取消选中该框,但实际上不应该,因为它必须选中一次并且应该停止。 我知道在实际场景中应该是这样的:

handleCheck(){
            this.setState ({
              checked: !this.state.checked
            })
          }

有人能告诉我为什么我可以多次选中和取消选中,即使我做错了吗?

最佳答案

您正在创建一个 controlled component ,它需要一个处理程序来更改状态,并且它的值/检查属性由状态控制。

您需要将 this.handleCheck 指定为 onChange 处理程序,并将 this.state.checked 指定为 checked属性值:

class Checkbox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      checked: false
    }
    this.handleCheck = this.handleCheck.bind(this)
  }

  handleCheck() {
    this.setState({
      checked: true
    })
  }

  render() {
    return (
      <div>
        <input 
          type="checkbox" 
          checked={this.state.checked}
          onChange={this.handleCheck}
          />
      </div>
    )
  }
}

ReactDOM.render( 
  <Checkbox /> ,
  document.getElementById("react-container")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='react-container'></div>

关于javascript - React JS 中的复选框绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460052/

相关文章:

javascript - 通过选中和取消选中复选框来添加和删除数组中的值

javascript - 具有水平滚动但单独页面的网站

javascript - 避免内联 javascript

javascript - jquery DataTable 搜索和排序不起作用

ReactJS:停止自动提交输入

ios - 在 RCTBridgeModule.h 中找不到 React/RCTDefines.h 文件

reactjs - React 中的 onClick "save image as"

oracle - 在生产中使用 Babel - 如何预编译脚本

javascript - React Native 中的逗号和解析错误

android - Android 上的 React Native Fetch 不会传递选项