'this' 在 reactjs 复选框上使用 onChange 事件时为空

'this' is null when working with onChange event on a reactjs check box

当用户单击它们(或与此相关的文本输入字段)时,我正在努力获取我的 react-js 代码更新单选按钮。首先是代码(略有缩写):

// (...)
@connect(mapStateToProps, mapDispatchToProps)
export default class EditMatch extends React.Component {
    render() {
        return (
            <div>
                <form>
                    <input
                        type="radio"
                        name="ms"
                        value="isPlayed"
                        checked={props.matchStatus === "isPlayed"}
                        onChange={this.stateChange}
                    />
                    Not played
                    <input
                        type="radio"
                        name="ms"
                        value="played"
                        checked={props.matchStatus === "played"}
                        onChange={this.stateChange}
                    />
                    Played
                </form>
            </div>
        );
    }

    stateChange(e) {
        console.log(e.currentTarget);
        console.log(this.props);
    }
}

控制台输出为:

<input type="radio" name="matchStatus" value="p2walkover" data-reactid=".109bqx8vjeo.0.0.1.3.1.2.0.1.2.0.7">
edit-match.js?6505:71 Uncaught TypeError: Cannot read property 'props' of undefined

所以基本上 'this' 是未定义的。所以我无法关注 并致电 this.setState.

我做错了什么?

使用 ES6 class 语法时,您的 class' 函数不会自动绑定到正确的上下文(就像使用 React.createClass 时那样)。This is documented in the React documentation .

您只需要稍微更新一下您的 onChange 处理程序:

onChange={(e) => this.stateChange(e)}

或:

onChange={this.stateChange.bind(this)}

您也可以根据 the blog post:

更改 class 函数定义
stateChange = (e) => {
    console.log(e.currentTarget);
    console.log(this.props);
}

现在您可以调用 this.stateChange 而无需预先绑定它。