ReactJS - 如何将组件暴露给外部事件?
ReactJS - 如何将组件暴露给外部事件?
我有两个组件:
- 父组件
- 子组件
我尝试从父组件调用子组件的方法,我尝试了以下方法但没有得到结果:
class Parent extends Component { render() { return ( ); } } class Child extends Component { getAlert() { alert('clicked'); } render() { return (
Hello
); } }
有没有一种方法可以从父组件调用子组件的方法?
注意:子组件和父组件位于两个不同的文件中。
admin 更改状态以发布 2023年5月22日
你可以在这里使用另一种模式:
class Parent extends Component { render() { return (this.clickChild = click}/> ); } } class Child extends Component { constructor(props) { super(props); this.getAlert = this.getAlert.bind(this); } componentDidMount() { this.props.setClick(this.getAlert); } getAlert() { alert('clicked'); } render() { return ( Hello
); } }
它的作用是在子组件挂载时设置父组件的clickChild
方法。这样,当你在父组件中点击按钮时,它会调用clickChild
,然后再调用子组件的getAlert
方法。
如果你的子组件被connect()
包裹,这种方法也可以使用,因此你不需要getWrappedInstance()
的hack方法。
请注意,你不能在父组件中使用onClick={this.clickChild}
,因为在父组件渲染时子组件尚未被挂载,所以this.clickChild
尚未被赋值。使用onClick={() => this.clickChild()}
是可以的,因为当你点击按钮时,this.clickChild
应该已经被赋值了。
首先要说的是,在React中通常不是这样做的。通常你想做的是把功能传递给子组件的属性中,并在事件中从子组件中获取通知(或者最好是使用 dispatch
)。
但是如果你必须在子组件上公开一个命令式的方法,您可以使用 Refs。请记住这是一个逃生口,通常表示有更好的设计可用。
以前,Refs只支持基于类的组件。随着 React Hooks 的出现,这已经不再是这样了。
使用Hooks实现现代React(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"); } })); returnHi
; }); 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 (); }; ReactDOM.render( , document.getElementById('root') );
useImperativeHandle()
的文档在这里:这里:
useImperativeHandle
定制了在使用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 (); } } class Child extends Component { getAlert() { alert('getAlert from Child'); } render() { return Hello
; } } ReactDOM.render(, document.getElementById('root'));
回调引用API
回调引用是另一种实现这一目的的方法,虽然在现代React中不太常见:
const { Component } = React; const { render } = ReactDOM; class Parent extends Component { render() { return ({ this.child = instance; }} /> ); } } class Child extends Component { getAlert() { alert('clicked'); } render() { return ( Hello
); } } render(, document.getElementById('app') );