简体   繁体   English

在反应中从孙功能组件调用祖父母方法

[英]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 我尝试使用的方法是TodoItem组件中App组件中的handleChangeStatus()

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);

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

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