【问题标题】:Why can't I access state and props inside event handler为什么我不能访问事件处理程序中的状态和道具
【发布时间】:2016-05-01 07:20:24
【问题描述】:

我已经写了这段代码

import React from 'react';
import DimensionPickerAction from '../actions/DimensionPickerActions.js';
import MovieLensAppStore from '../stores/MovieLensAppStore.js';

class DimensionPicker extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dimensionName: this.props.dimension,
            items: MovieLensAppStore.getAttributes(this.props.dimension),
            currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
        };
    }

    onSelectionChange(event) {
        console.log(event.target.value)
        DimensionPickerAction.selectionChange(temp.state.dimensionName, event.target.value);
    }

    render() {
        var optionNodes = this.state.items.map((item) => {
            return(<option key={item.id} value={item.val}>{item.val}</option>)
        });
        return(<div><select onChange={this.onSelectionChange} defaultValue={this.state.currentItem}>{optionNodes}</select></div>);
    }

}

export default DimensionPicker;

我可以看到,当方法 onSelectionChange 被调用时,状态和道具都为空。

我发现这个帖子讨论了同样的问题

Access props and state of current component in React JS within an event handler

但该解决方案对我不起作用。我尝试创建另一个方法,然后从 onSelectionChange 调用该方法,但该方法对事件处理程序也不可见。

我还尝试将 this 指针存储在临时变量中……但这会导致语法错误。

有人知道如何在事件处理程序中访问状态和道具吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    从 React .14 开始,事件处理程序不会自动绑定到组件的范围。

    你可以使用我讨厌的肮脏的 .bind(this) 方法,它就像这样很慢。

    render() {
        var optionNodes = this.state.items.map((item) => {
            return(<option key={item.id} value={item.val}>{item.val}</option>)
        });
        return(<div><select onChange={this.onSelectionChange.bind(this)} defaultValue={this.state.currentItem}>{optionNodes}</select></div>);
    }
    

    或者使用胖箭头函数来包装回调,这样更快并且不需要绑定范围,因为胖箭头函数在创建的范围内执行。

    render() {
        var optionNodes = this.state.items.map((item) => {
            return(<option key={item.id} value={item.val}>{item.val}</option>)
        });
        return(<div><select onChange={(event) => { this.onSelectionChange(event) }} defaultValue={this.state.currentItem}>{optionNodes}</select></div>);
    }
    

    【讨论】:

    • 这不是 React 0.14 的变化。扩展 React.Component(在 0.13 中引入)的组件从来没有自动绑定。使用React.createClass() 构造的组件仍然具有自动绑定功能。我以前在这里记录了这一点。 stackoverflow.com/questions/34505511/…
    • 哈。我站纠正!版本跟踪不是我的强项!考虑到远离 .createClass 的好处和总体方向,我的回答似乎仍然成立。
    • 或者你可以绑定类构造函数上的函数 this.functionName = this.functionName.bind(this);
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2019-10-16
    • 2021-08-26
    • 2021-09-24
    • 2021-09-29
    • 2011-07-26
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多