当前位置: 首页 > 面试题库 >

React-在子组件中调用父方法

吴建中
2023-03-14
问题内容

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

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

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


问题答案:

试试这个。将功能作为道具传递给子组件。

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中从父组件调用子组件方法。我试过使用裁判,但不能做到这一点。有没有人能提出任何解决方案。多谢了。

  • 本文向大家介绍Vue父组件调用子组件事件方法,包括了Vue父组件调用子组件事件方法的使用技巧和注意事项,需要的朋友参考一下 Vue父组件向子组件传递事件/调用事件 不是传递数据(props)哦,适用于 Vue 2.0 方法一:子组件监听父组件发送的方法 方法二:父组件调用子组件方法 子组件: 父组件: 以上这篇Vue父组件调用子组件事件方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希

  • 问题内容: 我想编写一个Form组件,该组件可以导出方法以验证其子级。不幸的是,表单没有“看到”其子级上的任何方法。 这是我定义Form的潜在子代的方法: 这是我定义Form类的方式: 我注意到可以使用引用在子组件上调用方法,但不能通过props.children调用方法。 这种React行为是否有原因? 我怎样才能解决这个问题? 问题答案: 技术原因是,当您尝试访问子组件时,它们尚未真正存在(在

  • 我已经创建了一个子组件,它有一个我想调用的方法。 当我调用这个方法时,它只触发行,它不会设置属性?? 下面是快速启动的Angular应用程序和我的更改。 家长 孩子 如何设置属性?

  • 我尝试了以下代码,但失败了,因此,这是我的父组件: 这是我的子组件: 在子组件中单击上面的按钮,我希望调用父方法。如何才能做到这一点?编辑

  • 我在react native中有一个搜索栏组件,它在父组件中导入, SearchBar子组件具有以下元素: 是否可以访问此子组件在其中导入的父组件中的状态?提前感谢你的帮助