父组件向子组件传值通过props传递,是很轻松的事。但在子组件中定义的useState,useRef值,要想在父组件中得到,却需要额外的props参数设置。
举例如下:
父组件:

子组件:
关键解释如下:
父组件:
bond是一个ReactRef对象,存储在useState中,通过Son组件的bond props传递给Son组件。在父组件中通过调用bond.current就能调用子组件中包裹在useImpreativeHandle函数中的子组件函数,对子组件进行操作,这里调用getSonName是获取Son组件中的sonName值
子组件:
既然父组件需要获取我的值,那么,我就需要将在我的作用域内定义的值开放出来,通过使用React自带的useImpreativeHandle hooks就能做到这一点。
源码:
import React, { useState } from "react";
import Son from "./Son"
export default function Farther () {
const [bond] = useState(React.createRef<{getSonName: () => string}>())
const [fartherName] = useState("john")
const sonName = bond.current?.getSonName()
console.log(sonName)
return <Son fartherName={fartherName} bond={bond} />
}
import React, { useImperativeHandle, useState } from "react";
export default function Son ({fartherName,bond}:{fartherName: string,bond: React.RefObject<{
getSonName: () => string
}>}) {
const [sonName] = useState("johnlove")
const getSonName = () => {
return sonName
}
useImperativeHandle(bond, () => {
return{
getSonName
}
})
return <>
{fartherName}
</>
}
3056

被折叠的 条评论
为什么被折叠?



