首先,让我表示一下,这通常是不在陆地上做出反应的方法。通常,您想要做的是将功能传递给道具中的子程序,并在事件中传递来自子级的通知(或者更好的是:dispatch).
但如果你必在子组件上公开一个命令式方法,您可以使用参考文献..记住,这是一个逃生舱口,通常表明一个更好的设计是可用的。以前,只支持基于类的组件。随着…的到来反应钩,现在不是这样了
使用钩子和函数组件(>= react@16.8)import React, { forwardRef, useRef, useImperativeHandle } 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
useImperativeHandle(ref, () => ({
getAlert() {
alert("getAlert from Child");
}
}));
return
Hi
;});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 (
childRef.current.getAlert()}>Click
);};
文件useImperativeHandle()是这里:useImperativeHandle时,自定义公开给父组件的实例值。ref.
使用类组件(>= react@16.4)class Parent extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
}
onClick = () => {
this.child.current.getAlert();
};
render() {
return (
Click
);
}}class Child extends Component {
getAlert() {
alert('getAlert from Child');
}
render() {
return
Hello
;}}ReactDOM.render(, document.getElementById('root'));
遗留API(<= react@16.3)
出于历史目的,下面是在16.3之前的Reaction版本中使用的基于回调的样式:
const { Component } = React;
const { render } = ReactDOM;
class Parent extends Component {
render() {
return (
{ this.child = instance; }} />
{ this.child.getAlert(); }}>Click
);
}
}
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
Hello
);
}
}
render(
,
document.getElementById('app')
);