javascript - 如何在子组件中调用父函数

标签 javascript reactjs

我检查了很多示例,但发现大多数示例都在子组件中触发了事件。
有人可以建议我如何使用父组件上的单击事件调用子组件的父组件功能吗?谢谢。

父组件(app.js):

Class App extends Component { 

    handleClick = (e, id, text) => {
        e.preventDefault();
        this.setState({val: text})
      }

      render() {
        return (
          <div>
            <Form val={this.state.val} Click={this.handleClick.bind(this) }/>
            <Button onClick={(e) => this.handleClick(e, todo.id, todo.text)}>
               <Icon>edit_icon</Icon>
            </Button>
        </div>
      )
   }
 }

子组件(form.js):

    this.props.Click(); //where should i call this function since my button is in parent component

Class Form extends Component{

    render() {
        const { text } = this.state;
        return (
          <TextField
              value={text}
              color="secondary"
          />
        )
      }
    }
}

最佳答案

如果你想在你的子组件中调用它,你需要一个事件来触发它或者可能是一个条件。因此,例如在您的 form.js 中,我们将通过从您的子组件单击按钮来触发它

render() {
    const { text } = this.state;
    return (
      <TextField
          value={text}
          color="secondary"
      />
      <Button onClick={this.props.Click} />
    )
  }
}

也许,在你的子组件中使用 Button 不是一个很好的选择,因为你已经有一个 Button 可以在你的父组件中调用 Click 函数,我制作的这个 Button in child component 只是为了举例

关于javascript - 如何在子组件中调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51393272/

相关文章:

javascript - react native onPress 事件不在循环中工作

reactjs - 如何在 Jest 中访问历史对象

reactjs - React hooks 中的依赖数组真的需要详尽无遗吗?

javascript - 如何增加 Javascript 下拉菜单在屏幕上保留的时间?

javascript - 允许用户垂直调整 block 的大小并使其下方的所有内容向后/向前推

javascript - 使用 Turbolinks 5 重构内联 &lt;script&gt; 元素

javascript - maxDelayTime 太长有什么坏处?

javascript - Django 模板不执行 js 函数

javascript - React App : EventSource's response has a MIME type ("application/json") that is not "text/event-stream". 中止连接

javascript - 使用变量作为 `this.state` 调用 ReactJS 的一部分