redux 来传值应该是最好的吧,还有useContext,待更。。。
一.父传子(简单-属性传值)
// 父组件
import { useState } from 'react'
import ChildCom from './learnUseforward'
const FatherCom = () => {
const [count, setCount] = useState(123456)
return (
<div>
<ChildCom data={ count }/>
</div>
)
}
export default FatherCom
// 子组件
function ChildCom (props) {
return (
<div>
{ props.data }
</div>
)
}
export default ChildCom
二.子传父(使用useRef)
// 父组件
import { useRef } from 'react'
import { Button} from 'antd'
import ChildCom from './learnUseforward'
const FatherCom = () => {
const childRef = useRef(null)
const handleGetChildData = () => {
const data = childRef.current.getFromData()
console.log('data', data)
}
return (
<div>
<ChildCom ref={ childRef }/>
<Button onClick={() => handleGetChildData()}>我要获取子组件的数据</Button>
</div>
)
}
export default FatherCom
// 子组件
import { useState, forwardRef, useImperativeHandle } from 'react'
import { Button } from 'antd'
function ChildCom (props, ref) {
const [formValue, setFormValue] = useState({name: 'ky', age: 18})
useImperativeHandle(ref, ()=>({
getFromData: ()=> {
return formValue
}
}))
return (
<div>
我是from组件
</div>
)
}
ChildCom = forwardRef(ChildCom)
//这里用forwardRef包裹住了,LearnUseforward必须以函数声明,不能是变量声明
export default ChildCom