【问题标题】:'this' is null when working with onChange event on a reactjs check box在 reactjs 复选框上使用 onChange 事件时,“this”为空
【发布时间】:2016-08-05 03:44:10
【问题描述】:

当用户单击我的 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 pattern 并致电this.setState

我做错了什么?

【问题讨论】:

    标签: reactjs jsx


    【解决方案1】:

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

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

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

    或者:

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

    您也可以按照the blog post 更改您的类函数定义:

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

    现在您无需预先绑定即可调用this.stateChange

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-20
      • 2018-04-25
      • 1970-01-01
      • 2018-04-21
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      相关资源
      最近更新 更多