一.父组件如何获取子组件数据
0.类组件: 相关文章可以搜下,百度搜 react cref
重点说下函数组件
1.函数组件:
在函数组件中要获取子组件的数据,需要两步骤
1.将ref传递到子组件中,
2.需要使用forwardRef对子组件进行包装
1.父组件:
export default () => {
const parentRef = useRef();
function focusHander() {
console.log(parentRef);
parentRef.current.focus();
parentRef.current.value = '哈哈';
}
return (
<>
<ForwardChild ref={parentRef} />
<button onClick={focusHander}>获取焦点</button>
</>
)
}
2.子组件:
function Child(props, parentRef) {
console.log(props);
return (
<>
<input type="text" ref={parentRef} />
</>
)
}
/**
* 使用forwardRef将ref直接传递进去
*/
let ForwardChild = forwardRef(Child);
export default ForwardChild;
2. 优化(使用 useImperativeHandle)
上面的方式都会将组件中全部的数据暴露出去,有时候我们想只想暴露出一部分数据
或者我们有时想把state里的数据暴露部分出去
1.父组件:
export default () => {
const parentRef = useRef();
const focusHandler = () => {
parentRef.current.focus();
console.log(parentRef)
}
return (
<>
<ForwardChidl ref={parentRef} name={'你好'} />
<button onClick={focusHandler}>获取焦点</button>
</>
)
}
2.子组件:
import React, { useState, useRef, useImperativeHandle, forwardRef } from 'react'
function Child(props, parentRef) {
const [data, setData] = useState([
{ name: 'agag', age: 88},
{ name: 'bb', age: 77},
{ name: 'cc', age: 66},
])
const inputRef = useRef();
useImperativeHandle(parentRef, () => {
// return返回的值就可以被父组件获取到,没返回的值就获取不到
return {
focus() {
inputRef.current.focus();
},
dataobj:data
}
})
const handleChange = () => {
setData([
...data,
{ name: 'ss', age: 99887},
])
}
return (
<>
<p>{props.name}</p>
<input type="text" ref={inputRef} />
<button onClick={handleChange}>改变son的值</button>
</>
)
}
let ForwardChidl = forwardRef(Child);
export default ForwardChild;
相关文章:
https://segmentfault.com/a/1190000041639103/
https://juejin.cn/post/7024786617105645581
https://www.cnblogs.com/xiao-yaolx/p/15693405.html
https://blog.51cto.com/u_3409716/2904219