1 Implementation method of function components:
parent component:
import React from "react";
import Child from './Child'
const Parent = ()=>{
const ChildRef = React.createRef();
return (
<div onClick={
() => ChildRef.current.handleChild()}>
<Child onRef={
ChildRef}/>
</div>
)
}
Subassembly:
import React, {
useImperativeHandle } from "react";
const Child = (props)=>{
useImperativeHandle(props.onRef, () => {
return {
handleChild: getList,
}
})
const getList = ()=>{
console.log('子组件方法') }
return <div>子组件</div>
}
2 types of component implementation:
parent component:
import React,{
Component} from 'react';
import Child from './Child'
export default class Parent extends Component{
componentDidMount () {
this.child.test('父组件参数')
}
onRef = (ref)=> {
this.child=ref
}
render () {
return (
<div>
<Child onRef={
this.onRef}/>
</div>
)
}
};
Subassembly:
import React,{
Component} from 'react';
export default class Child extends Component{
componentDidMount () {
this.props.onRef(this)
}
test = (val)=> {
console.log(val)
}
render () {
return <div>子组件</div>
}
};