React - 在子组件中调用父方法 [英] React - Call parent method in child component

查看:1366
本文介绍了React - 在子组件中调用父方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父子组件,我想在子组件中调用父方法,如下所示:

I have a parent and child compoents and I want to call a parent method in the child component like this:

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    click() {
        Parent.someMethod();
    }

    render() {
          <div>Hello Child onClick={this.click}</>
    }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        };

    someMethod() {
        console.log('bar');
    }

    render() {
          <div>Hello Parent</>
    }
}

这会返回错误消息:

未捕获的TypeError:_Parent2.default.someMethod不是函数

如何在子组件中调用此父方法?

How can this parent method be called in the child component?

推荐答案

试试这个。将该函数作为道具传递给子组件。

Try this. Passing the function down as props to the child component.

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    click = () => {
        this.props.parentMethod();
    }

    render() {
          <div onClick={this.click}>Hello Child</div>
    }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        };

    someMethod() {
        console.log('bar');
    }

    render() {
          <Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
    }
}

这篇关于React - 在子组件中调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆