在父組件中調(diào)用子組件中的方法
forwardRef 作用就是在函數(shù)組件中鄙早,將
在父組件中創(chuàng)建的ref
傳遞給子組件
,在父組件中通過ref
可以調(diào)用子組件的方法
枫甲。比如調(diào)用TextInput
源武、ScrollView
等本身帶有的方法
useImperativeHandle 給當(dāng)前的ref綁定方法(可以是父組件傳遞的,也可以是子組件自己創(chuàng)建的)
方法1:再父組件中創(chuàng)建 ref想幻,傳遞到子組件
父組件
export default NewsPage = ({navigation}) => {
// 在父組件中創(chuàng)建ref
const contentRef = useRef()
function onClick(){
//可以直接調(diào)用TextInpu的方法
contentRef.current.focus()
contentRef.current.abc()
// contentRef.current.scrollTo()
}
return <MainView style={styles.mainView}>
<NewContent ref={contentRef}/> // 傳遞給子組件
</MainView>
}
子組件
export default NewContent = forwardRef((props,ref) => {
useImperativeHandle(ref,()=>({
abc:()=>{
}
}))
return <View style={styles.topScroll}>
<TextInput ref={ref} .../>
/*<ScrollView ref={ref} .../>*/
</ScrollView>
</View>
})
方法2:再子組件中創(chuàng)建 ref粱栖,回傳到父組件
子組件
export default NewContent =({onBackRef}) => {
// 創(chuàng)建ref
const tRef = useRef()
useEffect(()=>{
onBackRef(tRef) // 回傳給父組件
},[])
useImperativeHandle(tRef,()=>({
abc:()=>{
}
}))
return <View style={styles.topScroll}>
<TextInput ref={tRef} .../>
</View>
}
父組件
export default NewsPage = ({navigation}) => {
return <MainView style={styles.mainView}>
<NewContent onBackRef ={(ref)=>{
ref.abc() // 在此調(diào)用子組件的方法
}}/>
</MainView>
}