繁体   English   中英

ReactJS从子组件修改父状态

[英]ReactJS modify parent state from child component

我点击时试图从状态数组中删除一个项目。 目前我有一个onclick监听器,它调用一个传递给道具的函数。 但是我得到一个警告:bind():React组件方法可能只绑定到组件实例。 请参阅应用程序...并且它不会删除该项目。

感谢您对此问题的任何帮助! 它几乎让我的进步陷入停顿。

(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实际上将方法自动绑定到当前组件:

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

在TodoList组件中,而不是:

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

尝试:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM