【问题标题】:Binding event handler prop with react-redux使用 react-redux 绑定事件处理程序道具
【发布时间】:2018-03-27 08:28:43
【问题描述】:

将事件处理程序从容器声明到表示小部件以便我可以访问事件处理程序函数中的其他道具的正确方法是什么?

class ApplicationWidget extends Component {
    componentDidMount() {
        this.props.handle_onload.call(this);
    }

    render() {
        return (
            <div onClick={this.props.handle_click}>
                <Header />
                <Content />
            </div>
        );
    }
}

export default connect(
    state => {
        return {foo: state.foo};
    },
    dispatch => {
        return {
            handle_click() {
                console.log(this)
            },
            handle_onload() {
                jQuery.get({
                    accepts: 'application/json',
                    success: (data) => dispatch(the_action_creator(data)),
                    url: `/initialize`
                });
            }
        };
    }
)(ApplicationWidget);

当前,每当单击事件发生时,this.props.handle_click 事件处理程序都会记录 undefined。如果我想访问this.props.foo,正确的做法是什么?我目前的实现是

<div onClick={this.props.handle_click.bind(this)}>

render() 方法中,它按预期工作,但是根据linter,这看起来不是一个好习惯。更新容器(由connect 函数生成)后,以下代码似乎不起作用(由于某种原因,绑定重置为undefined

constructor(props) {
    super(props);
    this.props.handle_click = this.props.handle_click.bind(this)
}

那么正确的方法是什么?还是我做错了整件事?

【问题讨论】:

  • 我知道因此我正在寻找正确的方法(:

标签: javascript reactjs ecmascript-6 redux react-redux


【解决方案1】:

prop handle_click 只是一个通过引用传递给组件的函数,因此它对组件的范围(this)一无所知。您可以使用对所有函数都可用的 bind 方法进行更改,如下所示:

class ApplicationWidget extends Component {
    componentDidMount() {
        this.props.handle_onload.call(this);
    }

    render() {
        return (
            <div onClick={this.props.handle_click.bind(this)}>
                <Header />
                <Content />
            </div>
        );
    }
}

为了优化这一点并防止你的 linter 抱怨,你可以像这样在构造函数中绑定它:

class ApplicationWidget extends Component {
    constructor(props) {
        super(props);
        this.handle_click = props.handle_click.bind(this);
    }

    componentDidMount() {
        this.props.handle_onload.call(this);
    }

    render() {
        return (
            <div onClick={this.handle_click}>
                <Header />
                <Content />
            </div>
        );
    }
}

所以你几乎是对的,但我不会修改构造函数中的道具,只是在类中添加另一个方法。

【讨论】:

  • 它是否适用于您的 Redux 设置?我只测试了一个简单的组件
猜你喜欢
  • 2017-01-26
  • 2016-05-26
  • 2023-03-11
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 2010-10-22
  • 1970-01-01
相关资源
最近更新 更多