从父母调用子方法 [英] Call child method from parent

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

问题描述

我有两个组件。


  1. 父组件

  2. 子组件

我试图从Parent调用child的方法,我试过这种方式但是无法得到结果

I was trying to call child's method from Parent, I tried this way but couldn't get a result

class Parent extends Component {
  render() {
    return (
      <Child>
        <button onClick={Child.getAlert()}>Click</button>
      </Child>
      );
    }
  }

class Child extends Component {
  getAlert() {
    alert('clicked');
  }

  render() {
    return (
      <h1 ref="hello">Hello</h1>
    );
  }
}

有没有办法从父母那里调用孩子的方法?

Is there a way to call child's method from the parent ?

注意:Child和Parent组件有两个不同的文件

Note: Child and Parent components are in two different files

推荐答案

您可以使用 refs


以前,refs仅支持基于类的组件。随着
React Hooks 的出现,已经不再是这样了

Previously, refs were only supported for Class-based components. With the advent of React Hooks, that's no longer the case



使用挂钩和功能组件



Using Hooks and Function Components

import React, { forwardRef, useRef, useImperativeMethods } from 'react';

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {

  // The component instance will be extended
  // with whatever you return from the callback passed 
  // as the second argument 
  useImperativeMethods(ref, () => ({

    getAlert() {
      alert("getAlert from Child");
    }

  }));

  return <h1>Hi</h1>;
});

const Parent = () => {
  // In order to gain access to the child component instance,
  // you need to assign it to a `ref`, so we call `useRef()` to get one
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
};

功能示例

useImperativeMethods()的文档是这里


useImperativeMethods 自定义使用 ref 时公开给父组件的实例值。

useImperativeMethods customizes the instance value that is exposed to parent components when using ref.



使用类组件



Using Class Components

class Parent extends Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
  }

  onClick = () => {
    this.child.current.getAlert();
  };

  render() {
    return (
      <div>
        <Child ref={this.child} />
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

class Child extends Component {
  getAlert() {
    alert('getAlert from Child');
  }

  render() {
    return <h1>Hello</h1>;
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'));

功能示例

出于历史目的,这里是你在16.3之前使用React版本的基于回调的样式:

For historical purposes, here's the callback-based style you'd use with React versions before 16.3:

const { Component } = React;
const { render } = ReactDOM;

class Parent extends Component {
  render() {
    return (
      <div>
        <Child ref={instance => { this.child = instance; }} />
        <button onClick={() => { this.child.getAlert(); }}>Click</button>
      </div>
    );
  }
}

class Child extends Component {
  getAlert() {
    alert('clicked');
  }

  render() {
    return (
      <h1>Hello</h1>
    );
  }
}


render(
  <Parent />,
  document.getElementById('app')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

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

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