ReactJS从子组件修改父状态 [英] ReactJS modify parent state from child component

查看:92
本文介绍了ReactJS从子组件修改父状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击时从状态数组中删除一个项目.目前,我有一个onclick侦听器,该侦听器调用传递到props中的函数.但是我得到一个警告:bind():React组件方法只能绑定到组件实例.请参阅"App ...",它不会删除该项目.

I'm trying to remove an item from my state array when clicked. At the moment I have an onclick listener which calls a function passed into the props. However I get a warning: bind(): React component methods may only be bound to the component instance. See App... and it does not remove the item.

感谢您对此问题的任何帮助!这几乎使我的进展停了下来.

Thanks for any help regarding this issue! It has pretty much ground my progress to a halt.

(function (React) {

var data = [
    'Go to work',
    'Play Albion Online',
    'Keep learning React'
]

var App = React.createClass({
    getInitialState: function () {
        return {data: []}
    },
    componentWillMount: function () {
        this.state.data = data;
    },
    removeItem: function (i) {
        console.log(i);
    },
    render: function () {
        return (
        <ToDoList onRemoveItem={this.removeItem} tasks={this.state.data} />
        )
    }
});

var ToDoList = React.createClass({
    render: function () {

        var scope = this;

        var tasks = this.props.tasks.map(function (task, i) {
            return <ToDo onClick={scope.props.onRemoveItem.bind(this, i)} key={task} task={task} />
        });

        return (
        <ul>
            {tasks}
        </ul>
        )
    }
});

var ToDo = React.createClass({
    render: function () {
        return (
            <li>{this.props.task}</li>
        )
    }
});

React.render(<App />, document.getElementById('example'));
})(React);

推荐答案

实际上将方法自动绑定到当前组件:

React actually auto-binds methods to the current component:

http://facebook.github .io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html

在TodoList组件中,而不是:

In the TodoList component, rather than:

scope.props.onRemoveItem.bind(this, i)

尝试:

scope.props.onRemoveItem.bind(null, i)

通过提供null而不是this,您将允许React做自己的事情.另外,您还需要实际使用onClick处理程序:

By providing null instead of this you'll allow React to do its own thing. Also you need to actually use the onClick handler:

<li onClick={this.props.onClick}>{this.props.task}</li>

这篇关于ReactJS从子组件修改父状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆