javascript - 从父调用子方法

标签 javascript reactjs

我有两个组件:

  1. 父组件
  2. 子组件

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

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

有没有办法从 Parent 调用 Child 的方法?

注意:子组件和父组件位于两个不同的文件中。

最佳答案

首先,让我表达一下,这通常不是在 React 领域中处理事情的方式。通常你想要做的是在 props 中将功能传递给 child ,并在事件中传递来自 child 的通知(或者更好的是:dispatch)。

但如果您必须在子组件上公开命令式方法,则可以使用 refs .请记住,这是一个逃生舱口,通常表明有更好的设计可用。

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

现代 React 与 Hooks (v16.8+)

const { forwardRef, useRef, useImperativeHandle } = 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
  useImperativeHandle(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>
  );
};

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

useImperativeHandle() 的文档是 here :

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

使用类组件的旧版 API (>= react@16.4)

const { Component } = React;

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'));
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>

回调引用 API

回调样式的 refs 是实现此目的的另一种方法,尽管在现代 React 中并不常见:

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>

关于javascript - 从父调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949981/

相关文章:

javascript - Jest.fn() 在 React 单元测试中不起作用

javascript - 仪表条不更新

javascript - 在 iPhone 上查看完整网站,而非手机版

javascript - Particles.js 中的多个图像作为形状

javascript - 将绝对路径转换为相对路径

javascript - 根据单独的 json 对象中的值在 React.js 中创建一个新对象

reactjs - react-google-maps:如何使用 fitBounds、panBy、panTo、panToBounds 公共(public) API?

javascript - 在 React 中使用 Buttons 触发 react-table 上的过滤功能

javascript - 在 react 中传递 Prop 并显示在列表中的方法

django - 为 django api 设置消费者驱动的契约(Contract)测试并 react 客户端的合适方法是什么?