react.js中的基本复选框

时间:2016-06-03 04:12:25

标签: javascript reactjs

我刚刚开始学习React并尝试制作非常简单的复选框组件并收到错误未捕获TypeError:无法读取属性'已检查' null ,我无法弄清楚为什么我会这样,任何人都可以帮助我吗?

<div id="react-container">
    </div>
    <script   type="text/babel">

    class Checkedbox extends React.Component{
        initialState(){
          return { checked: false }
        };
        handelCheck(){
            this.setState({checked: !this.state.checked })
        };
        render(){
            var msg ;
            if(this.state.checked){
                 msg = 'Agree';
            } else {
                 msg = 'Disagree';
            }
            return (
                   <div>
                       <label for="mybox"> Opinion : </label>
                       <input type="checkbox"  id="mybox" onChange={this.handleCheck}
                              defaultChecked={this.state.checked}/>
                       <p>Hi i {msg} with it!</p>
                   </div>
            )
        };
    }
    let target = document.getElementById('react-container');
    ReactDOM.render(   < Checkedbox />,target)
    </script>

4 个答案:

答案 0 :(得分:0)

sum_rain

更改为

df

答案 1 :(得分:0)

将initialState()更改为getInitialState()。

答案 2 :(得分:0)

我猜this不属于实际元素:

handelCheck(){
    let that = this;
    this.setState({checked: !that.state.checked })
};

答案 3 :(得分:0)

试试这段代码。它应该工作

class Checkedbox extends React.Component{
            constructor(){
              super();
              this.state = { checked: false }
            }
            handleCheck = () => {
                this.setState({checked: !this.state.checked })
            }
            render(){
                var msg ;
                if(this.state.checked){
                     msg = 'Agree';
                } else {
                     msg = 'Disagree';
                }
                return (
                       <div>
                           <label for="mybox"> Opinion : </label>
                           <input type="checkbox"  id="mybox" onChange={this.handleCheck}
                                  defaultChecked={this.state.checked}/>
                           <p>Hi i {msg} with it!</p>
                       </div>
                )
            };
        }
        let target = document.getElementById('react-container');
        ReactDOM.render(   < Checkedbox />,target)