Javascript 反应:如何选中和取消选中复选框

Javascript 反应:如何选中和取消选中复选框,javascript,reactjs,Javascript,Reactjs,我写了这个组件: import React from 'react'; export default class Todo extends React.Component { constructor(props) { super(props); // Set initial state this.state = { data: props.data } } changeS

我写了这个组件:

import React from 'react';
    
export default class Todo extends React.Component {
    constructor(props) {
        super(props);

        // Set initial state
        this.state = {
            data: props.data
        }
    }

    changeStatus() {
        // This throws: Uncaught TypeError: Cannot read property 'state' of undefined
        console.log(this.state);
        console.log('status changed');
    }

    render() {
        let status = this.state.data.opened ? 'opened' : 'closed';
        return (
            <li className={"todo " + status} data-endpoint={this.state.data['@id']}>
                <div className="status">
                    <input type="checkbox" checked={!this.state.data.opened} onChange={this.changeStatus}/>
                </div>
                <a href={window.Routing.generate('todo_list_todo_show', {account: this.props.todoList.account.id, list: this.props.todoList.id, todo: this.state.data.id}, true)}>{this.state.data.name}</a>
            </li>
        );
    }
}
从“React”导入React;
导出默认类Todo扩展React.Component{
建造师(道具){
超级(道具);
//设置初始状态
此.state={
数据:道具数据
}
}
更改状态(){
//这将抛出:uncaughttypeerror:无法读取未定义的属性“state”
console.log(this.state);
console.log('status changed');
}
render(){
让status=this.state.data.opened?'opened':'closed';
返回(
  • ); } }
    我希望复选框被选中和取消选中,这取决于对服务器的调用以更新数据库中的行

    不幸的是,
    console.log()
    抛出了一个异常:

    未捕获的TypeError:无法读取未定义的属性“state”

    处于变更状态(Todo.jsx:20)


    如何在处理状态更改的方法中访问
    状态

    在构造函数中绑定
    更改状态
    方法-

    constructor(props) {
            super(props);
    
            // Set initial state
            this.state = {
                data: props.data
            }
            this.changeStatus = this.changeStatus.bind(this);
    
        }
    

    您可以阅读为什么需要绑定。

    如果您使用的是ES6,您可以通过使用箭头函数避免键入绑定

    changeStatus = () => {
            // This throws: Uncaught TypeError: Cannot read property 'state' of undefined
            console.log(this.state);
            console.log('status changed');
        }
    
    这样
    将自动绑定到函数

    changeStatus = () => {
            // This throws: Uncaught TypeError: Cannot read property 'state' of undefined
            console.log(this.state);
            console.log('status changed');
        }
    
    箭头函数在词汇上绑定其上下文,因此
    这实际上是指
    到原始上下文


    请尝试
    onChange={this.changeStatus.bind(this)}
    这应该是一条注释。我看到过很多类似的帖子。我们应该寻找这样的帖子,关闭这个帖子,而不是answering@Rajesh请原谅我重复:(@Aerendir让我们从现在开始努力保持纪律。:-)