这里写目录标题
子组件获取父组件
可通过props接收
<ChildList parentRef={parentRef} name={name}></ChildList>
父组件获取子组件
useRef将ref绑定到某个子组件标签上,用以获取整个子组件的方法和参数
useImperativeHandle: 可以自定义暴露给父组件的方法或者变量
父组件
import React, { useState, useRef } from 'react'
import ChildList from './ChildList'
export default () => {
let parentRef = useRef(null)
const [name, setName] = useState('li')
return <div>
<ChildList parentRef={parentRef} name={name}></ChildList>
<button onClick={() => {
console.log("parentRef", parentRef)
}}>获取子组件</button>
</div>
}
子组件
import React, { useImperativeHandle, forwardRef } from 'react'
export default forwardRef((props) => {
console.log("props", props)
const { parentRef } = props;
useImperativeHandle(parentRef, () => {
return {
childFn
}
})
console.log(parentRef)
const childFn = () => {
console.log('子组件方法')
}
return <div>
<div ref={parentRef} />
</div>
})
类组件中父组件获取子组件
当在子组件中调用onRef函数时,正在调用从父组件传递的函数。this.props.onRef(this)这里的参数指向子组件本身,父组件接收该引用作为第一个参数:onRef = {ref =>(this.child = ref)}然后它使用this.child保存引用。之后,可以在父组件内访问整个子组件实例,并且可以调用子组件函数。
// 父组件
class Parent extends React.Component {
handleClick=()=>{
this.child.handleChildClick() // -> 通过this.child可以拿到child所有状态和方法
}
render() {
return <div>
<ChildList onRef={(ref) => {this.child = ref}} />
<button onClick={this.handleClick}>父组件按钮</button>
</div>
}
}
// 子组件
class ChildList extends React.Component {
constructor(props) {
super(props)
}
componentDidMount(){
this.props.onRef(this)// ->将child自己传递给this.props.onRef()方法
}
handleChildClick=()=>{
console.log('通过父组件按钮获取到子组件信息啦啦啦')
}
render(){
return <div>我是子组件</div>
}
}