React Native - 使用 useRef 的钩子调用无效

时间:2021-01-15 13:25:11

标签: reactjs react-native react-native-navigation

我正在尝试在 React Native 的一个组件中使用 useRef(),但我不断收到

<块引用>

组件异常:无效的挂钩调用。钩子只能被调用 函数组件主体内部

我的组件:

import React, { createRef, useRef } from 'react';
import { Animated, View } from 'react-native';

const BottomTabMenu: React.FC = ({ navigation, state: { routeNames } }) => {

  const xPosition = useRef(new Animated.Value(0)).current;


  return (
    <Container>

      <Animated.View style={{ 
          position: 'absolute', left: 37, top: 32,
          transform: [
            {
              translateX: xPosition
            }
          ]
       }}>
        <LinearGradient
          start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
          colors={['#FF151B', '#AA0089']}
          style={{
            height: 40, width: 50, borderRadius: 20 }}>
        </LinearGradient>
      </Animated.View>


      <BottomTabMenuItem icon={require('../assets/performance.png')} title="Performance" onPress={() => navigation.navigate('Performance')} />
      <BottomTabMenuItem icon={require('../assets/wallet.png')} title="Carteira" onPress={() => navigation.navigate('Wallet')} />
      <BottomTabMenuItem icon={require('../assets/transactions.png')} title="Extrato" onPress={() => navigation.navigate('Transactions')} />
      <BottomTabMenuItem icon={require('../assets/settings.png')} title="Ajustes" onPress={() => navigation.navigate('Settings')} />

    </Container>
  )
}

我在其他组件中使用过 useRef 没有任何问题.. 特别是这个是底部选项卡选项卡..

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

原来我在BottomTabNavigator组件中以错误的方式调用了这个组件..

之前:

<TabMenu.Navigator initialRouteName="Performance" tabBar={BottomTabMenu}>
  <TabMenu.Screen name="Performance" component={Performance} />
  <TabMenu.Screen name="Wallet" component={Wallet} />
  <TabMenu.Screen name="Transactions" component={Transactions} />
  <TabMenu.Screen name="Settings" component={Settings} />
</TabMenu.Navigator>

之后:

<TabMenu.Navigator initialRouteName="Performance" tabBar={props => <BottomTabMenu {...props} />}>
  <TabMenu.Screen name="Performance" component={Performance} />
  <TabMenu.Screen name="Wallet" component={Wallet} />
  <TabMenu.Screen name="Transactions" component={Transactions} />
  <TabMenu.Screen name="Settings" component={Settings} />
</TabMenu.Navigator>

这段代码 tabBar={props => <BottomTabMenu {...props} />} 起到了作用..

感谢@CharlesKornoelje 和@RowanX 的帮助

答案 1 :(得分:0)

尝试执行以下操作:

  const xPosition = React.useRef<HTMLElement | null>( new Animated.Value(0)).current

useRef 接收类型与 useState 钩子相同。你只需要将它传递到 <>.