[英]React Native How to Access Child's Ref from Parent
我正在尝试从父组件访问子组件的 ref,但我失败了。 我有标签导航,从标签导航我想打开一个底部工作表,所以我需要从标签导航到达底部工作表的参考。 这是我的代码 =>
const addPostSheet = React.forwardRef((_, ref) => {
const sheetRef = ref
const renderContent = () => {
<View style={styles.panel}>
<TouchableOpacity style={styles.panelButton}>
<Text style={styles.panelButtonTitle}>Take Photo</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.panelButton}>
<Text style={styles.panelButtonTitle}>Choose From Library</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.panelButton} onPress={sheetRef.current.snapTo(1)}>
<Text style={styles.panelButtonTitle}>Cancel</Text>
</TouchableOpacity>
</View>
}
const fall = new Animated.Value(1)
return(
<View style={styles.container}>
<BottomSheet
ref={sheetRef}
snapPoints={[330, 0]}
renderContent={renderContent}
initialSnap={1}
enabledGestureInteraction={true}
enabledBottomInitialAnimation={true}
callbackNode={fall}
/>
</View>
)
})
const BottomTabNavigator = () => {
const sheetRef = useRef(null)
return (
<Tab.Navigator
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName
if (route.name === "home"){
iconName = focused ? 'ios-home' : 'ios-home-outline'
color = 'black'
size = 32
} else if (route.name === "add"){
iconName = focused ? 'add-circle-sharp' : 'add-circle-outline'
color = 'orange'
size = 32
} else if (route.name === "search"){
iconName = focused ? 'search' : 'search-outline'
color = 'black'
size = 32
}
return <Ionicons name={iconName} size={size} color={color}/>
},
})}
initialRouteName="home"
tabBarOptions={{
showLabel: false
}}
>
<Tab.Screen name="home" component={DrawerNavigator}/>
<Tab.Screen name="add" component={addPostSheet} listeners={({navigation}) => ({
tabPress: event => {
sheetRef.current.snapTo(0)
}
})} />
<Tab.Screen name="search" component={SearchStack}/>
</Tab.Navigator>
)
}
但是,我得到了Cannot read property "snapTo" of null
错误,我认为父母的引用一直保持为null
。 那么如何从 Tab Navigation 影响BottomSheet
?
不知道你的问题解决了没有。
在您的应用程序执行 sheetRef.current.snapTo(0) 之前,您希望将引用存储在一个局部变量中。 例如,你写
const storedRef = sheetRef.current;
然后,就在以下代码执行之前
tabPress: event => {
sheetRef.current.snapTo(0)
你运行以下行
sheetRef.current = storedRef;
这会指示 sheetRef 使用正确的 refs。
这样做使我能够解决与您类似的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.