父组件事件触发子组件中的事件
1:父组件是class,子组件是class
//父组件
import React, { Component } from 'react';
class Index extends Component {
click = (e) => {
this.childReset ?.onReset?.();
}
render() {
return (
<div>
<Button onClick={this.click} />
<Child ref={(node) => { this.childReset = node }} />
</div>
)
}
}
//子组件
class Child extends Component {
onReset=()=>{
alert('child')
}
render() {
return (<div>child</div>)
}
}
2:父组件是Component,子组件是hook
import React, { Component } from 'react';
class Index extends Component {
click = () => {
this.childReset && this.childReset ()
}
render() {
return (
<div>
<Button onClick={this.click} />
<Child ref={(node) => { this.childReset = node }} />
</div>
)
}
}
//子组件
import React, {useImperativeHandle,forwardRef } from 'react';
const Child = ({ ... },ref)=> {
useImperativeHandle(ref, () => onRest);
const onRest=()=>{
console.log('dddd');
};
return (<div onClick={onRest}>child</div>);
};
export default forwardRef(Child);
3:父组件是hook,子组件是Component
//父组件
import React, { useRef } from "react";
const Parent = ({
...
}) => {
const childReset = useRef()
const click=()=>{
childReset ?.current?.onReset?.();
}
return (
<div>
<Button onClick={click} />
<Child ref={childReset } />
</div>
)
}
//子组件
class Child extends Component {
onReset=()=>{
alert('child')
}
render() {
return (<div>child</div>)
}
}
4:父组件是hook,子组件是hook
//父组件
import React, { useRef } from "react";
const Parent = ({
...
}) => {
const childReset = useRef()
const click=()=>{
childReset ?.current?.();
}
return (
<div>
<Button onClick={click} />
<Child ref={childReset } />
</div>
)
}
import React, {useImperativeHandle,forwardRef } from 'react';
const Child = ({ ... },ref)=> {
useImperativeHandle(ref, () => onRest);
const onRest=()=>{
console.log('dddd');
};
return (<div >child</div>);
};
export default forwardRef(Child);