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

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</>
    }
}

这将返回一条错误消息:

Uncaught TypeError: _Parent2.default.someMethod is not a function

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

推荐答案

试试这个.将函数作为props 传递给子组件.

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>
    }
}

Reactjs相关问答推荐

表格提交中的react 路由导航

react 副作用循环

两条react 路由的行为不同.有没有人能解释一下,我已经找了好几天了

如何在Reac.js中通过子组件和props 调用父组件函数?

Next.js Next-Auth登录函数重定向到http://localhost:3000/api/auth/error

透明MOV文件未出现在我的React网页中

React useContext 的未定义返回值

React Wordpress Apache 在索引之外重新加载 -> 未找到页面

Next.js 和理智 | npm run build 时预渲染页面/时发生错误

部署到github pages时请求路径错误

Formik onChange() 字段挂钩覆盖显示值和 Select 机制

RTK 查询Mutations 在 StrictMode 中执行两次

docker:来 automorphic 护进程的错误响应:未指定命令.的原因是什么?

未捕获的类型错误:useSelector 不是函数

在 redux 中分派到另一个减少时状态值不会改变

ReactJs 行和列

react-markdown 不渲染 Markdown

未捕获的错误:操作必须是使用 redux/toolkit 的普通对象

设置 Material UI 表格默认排序

如何将本地视频文件上传到 Google Cloud