简体   繁体   English

React传递prop到其他组件以从状态数组中删除

[英]React pass prop to other component to delete from state array

I am working on a todo application to understand the power of react. 我正在研究todo应用程序,以了解反应的力量。 I created 3 components, which I will show you below. 我创建了3个组件,我将在下面向您展示。 So I would like to delete an todo from an array state which is located in an other component. 所以我想从一个位于另一个组件中的数组状态中删除一个待办事项。

Take a look at my components below. 看看下面的组件。

This is my TodoAppComponent: 这是我的TodoAppComponent:

import AddTodoComponent from '../AddTodoComponent/AddTodoComponent';

class TodoAppComponent extends Component {
  render() {
    return (
        <div id="page-content-wrapper">
            <div className="container">
                <div className="row">
                    <div className="col-lg-6 col-lg-offset-3">
                        <h1 className="m-b-md">What needs to be done?</h1>

                        <AddTodoComponent></AddTodoComponent>
                    </div>                         
                </div>
            </div>
        </div>
    );
  }
}

export default TodoAppComponent;

Here I have the TodoItemComponent: 这里我有TodoItemComponent:

class TodoItemComponent extends Component {
  deleteTodo(todo){
      console.log('deleteTodo', todo);
      this.props.onDelete(this.props.todo);
  }



  render() {
      console.log('this.props.todo', this.props.todo);

return (
    <div>            
        <li className="list-group-item todo-item">
            <button className="btn btn-xs btn-react btn-circle m-r-md">
                <span className="fa fa-check"></span>
            </button>
            {this.props.todo}
            <span className="pull-right">
                <button className="btn btn-xs btn-react btn-circle m-r-xs">
                    <span className="fa fa-pencil-square-o"></span>
                </button>

                <button className="btn btn-xs btn-react btn-circle" onClick={this.deleteTodo.bind(this.props.todo)}>
                    <span className="fa fa-trash-o"></span>
                </button>
            </span>
        </li>
    </div>
);

} } }}

export default TodoItemComponent ; export default TodoItemComponent ;

class TodoItemComponent extends Component {
  deleteTodo(){
    // this.setState({
    //   data: update(this.state.data, {$splice: [[index, 1]]})
    // })
    console.log('deleteTodo', this.props.todo);
  }


  render() {      
    console.log(this.props.todo, this.props.title);

    return (
        <div>            
            <li className="list-group-item todo-item">
                <button className="btn btn-xs btn-react btn-circle m-r-md">
                    <span className="fa fa-check"></span>
                </button>
                {this.props.todo}
                <span className="pull-right">
                    <button className="btn btn-xs btn-react btn-circle m-r-xs">
                        <span className="fa fa-pencil-square-o"></span>
                    </button>

                    <button className="btn btn-xs btn-react btn-circle" onClick={this.deleteTodo}>
                        <span className="fa fa-trash-o"></span>
                    </button>
                </span>
            </li>
        </div>
    );
  }
}

export default TodoItemComponent;

Here is the AddTodoComponent: 这是AddTodoComponent:

import TodoItemComponent from '../TodoItemComponent/TodoItemComponent';

class AddTodoComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            todo: '',
            todoArray: []
        };
    }

    addTodo(e){
        this.setState({ todo: e.target.value });
        this.state.todoArray.push(<TodoItemComponent todo={this.state.todo} onDelete={this.delete}></TodoItemComponent>);
    }

    delete(index){
    //     this.setState({
    //         todoArray: update(this.state.todoArray, {$splice: [[index, 1]]})
    //     });

        console.log('testDelete', this.state.todoArray);
    }

    handleChange(e){
        this.setState({ todo: e.target.value });
    }

    render() {
        return (            
            <div>
                <div className="input-group m-b-md">
                    <input type="text" className="form-control add-todo" placeholder="Todo..." value={this.state.todo} onChange={this.handleChange.bind(this)} />
                    <span className="input-group-btn">
                        <button className="btn btn-react" type="button" onClick={this.addTodo.bind(this)}>Add</button>
                    </span>
                </div>
                <ul className="list-group">
                    {this.state.todoArray}
                </ul>
            </div>
        );
    }
}

export default AddTodoComponent;

As you see I try to log this.props.todo when clicked on the delete button, so when it emits the deleteTodo function in TodoItemComponent. 如您所见,我在单击删除按钮时尝试记录this.props.todo ,因此当它在deleteTodo function中发出deleteTodo function时。 Where it returns me Uncaught TypeError: Cannot read property 'props' of null but in the render() method it is recognized and logs the outcome of the input. 它返回的地方Uncaught TypeError: Cannot read property 'props' of null但在render()方法中它被识别并记录输入的结果。

Thereby I tried to bind the prop in the deleteTodo function in the TodoItemComponent : 从而我试图支柱结合在所述deleteTodo功能TodoItemComponent

            <button className="btn btn-xs btn-react btn-circle" onClick={this.deleteTodo.bind(this.props.todo)}>
                <span className="fa fa-trash-o"></span>
            </button>

So the function looked like this: 所以函数看起来像这样:

deleteTodo(todo){
      console.log('deleteTodo', todo);
      this.props.onDelete(this.props.todo);
  }

Could somebody help me out on this issue? 有人可以帮我解决这个问题吗?

Your issue is the misuse of Function.prototype.bind here: 您的问题是在这里滥用Function.prototype.bind

onClick={this.deleteTodo.bind(this.props.todo)}
//                            ^ you're binding todo as the context

The first argument should be the context of the bound function, ie this , not the todo. 第一个参数应该是绑定函数的上下文,即this ,而不是todo。

onClick={this.deleteTodo.bind(this)}

And you should use this.props.todo within the deleteTodo function (which now has a proper context). 你应该在deleteTodo函数中使用this.props.todo (现在它有一个适当的上下文)。

Alternatively, you can an arrow function (which maintains it's outer context) to pass the todo : 或者,您可以使用箭头函数 (维护它的外部上下文)来传递todo

onClick={() => this.deleteTodo(this.props.todo)}

and your deleteTodo method would receive the todo as its first argument. 并且您的deleteTodo方法将接收todo作为其第一个参数。

Store data in this.state and only create React elements in render , something like the following: 将数据存储在this.state ,只在render创建React元素,如下所示:

class AddTodoComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            todo: '',
            todoArray: []
        };
    }

    addTodo(e){
        this.state.todoArray.push(e.target.value);
        this.setState({ todo: '' });
    }

    delete(index){
        console.log('testDelete', this.state.todoArray);
    }

    handleChange(e){
        this.setState({ todo: e.target.value });
    }

    render() {
        return (            
            <div>
                <div className="input-group m-b-md">
                    <input type="text" className="form-control add-todo" placeholder="Todo..." value={this.state.todo} onChange={this.handleChange.bind(this)} />
                    <span className="input-group-btn">
                        <button className="btn btn-react" type="button" onClick={this.addTodo.bind(this)}>Add</button>
                    </span>
                </div>
                <ul className="list-group">
                    {this.state.todoArray.map((todo, index) => (
                      <TodoItemComponent todo={todo} onDelete={this.delete.bind(this, index)}></TodoItemComponent>
                    ))}
                </ul>
            </div>
        );
    }
}

暂无
暂无

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

相关问题 React Redux state 数组变量作为道具传递给子组件,无限循环或空数组 - React Redux state array variable pass as prop to child component, either infinite loop or empty array 无法将数组作为道具传递给反应组件并渲染它 - not able to pass a array as prop to react component and render it 在 REACT.js 中,如何将状态从子组件传递到父组件作为道具 - In REACT.js how can I pass a state from child component up to Parent component as a prop React:如何从组件传递宽度作为支撑 - React: How to pass width as a prop from the component 在反应中传递状态或道具以将值传递给子组件 - Passing a state or prop to pass a value to child component in react React.js如何从this.props数组中将index作为prop传递给子组件 - React.js how to pass in index as prop to child component from this.props array 需要一个函数,使用 lodash 从数组中的两个嵌套对象中解析出数据,并将其作为 prop 传递给 react 组件 - Need a function that parse out data from two nested objects in an array using lodash and pass it as a prop in a react component 如何将 function(在数组内)作为 prop 传递给 React 中的子组件 - How to pass a function (within an array) as a prop to a sub component in React 我们可以将 setState 作为 props 从一个组件传递到另一个组件,并在 React 中从子组件更改父状态吗? - Can we pass setState as props from one component to other and change parent state from child component in React? 反应组件中的错误传递道具 - Wrong pass prop in react component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM