简体   繁体   中英

calling grandparent method from grandchild functional component in react

I'm trying to call a simple method from the grandparent component in my child component but from some reason I can't , I tried every possible way but I think I'm missing something here's the full code :

 import React, { Component } from 'react'; import './App.css'; var todos = [ { title: "Example2", completed: true } ] const TodoItem = (props) => { return ( <li className={props.completed ? "completed" : "uncompleted"} key={props.index} onClick={props.handleChangeStatus} > {props.title} </li> ); } class TodoList extends Component { constructor(props) { super(props); } render () { return ( <ul> {this.props.todosItems.map((item , index) => ( <TodoItem key={index} {...item} {...this.props} handleChangeStatus={this.props.handleChangeStatus} /> ))} </ul> ); } } class App extends Component { constructor(props) { super(props); this.state = { todos , text :"" } this.handleTextChange = this.handleTextChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleChangeStatus = this.handleChangeStatus(this); } handleTextChange(e) { this.setState({ text: e.target.value }); } handleChangeStatus(){ console.log("hello"); } handleSubmit(e) { e.preventDefault(); const newItem = { title : this.state.text , completed : false } this.setState((prevState) => ({ todos : prevState.todos.concat(newItem), text : "" })) } render() { return ( <div className="App"> <h1>Todos </h1> <div> <form onSubmit={this.handleSubmit}> < input type="text" onChange={this.handleTextChange} value={this.state.text}/> </form> </div> <div> <TodoList handleChangeStatus={this.handleChangeStatus} todosItems={this.state.todos} /> </div> <button type="button">asdsadas</button> </div> ); } } export default App; 

The method im trying to use is handleChangeStatus() from the App component in the TodoItem component

Thank you all for your help

This line is wrong:

this.handleChangeStatus = this.handleChangeStatus(this);

//Change to this and it works

this.handleChangeStatus = this.handleChangeStatus.bind(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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