12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React Navigation】StackNavigatorの入れ子したcomponentにpropsを渡す

Posted at

React Navigationで<Stack.Screen name="Home" component={HomeScreen}>という風にcomponentを渡すときに、どうやってHomeScreenにpropsを渡すのか迷ったのでメモ

結論

HomeScreen.js
export default function HomeScreen({ navigation, count, setCount }) {
  return (
    <View>
      <p>You clicked {count} times</p>
      <Button
        title="カウント"
        onPress={() => {
          setCount(count + 1)
        }
        />
    </View>
  );
}
HomeNavigator.js
const Stack = createStackNavigator()
export default function HomeNavigator() {
  const [count, setCount] = useState(1)
  const navigation = useNavigation()

  return(
    <Stack.Navigator>
      <Stack.Screen name="Home">
        { () => <HomeScreen navigation={navigation} setCount={setCount} count={count} /> }
      </Stack.Screen>
    </Stack.Navigator>
  )
}

Stack.Screenの入れ子として{ () => <HomeScreen /> }を渡し、propsで値を渡すようにする

詰まって表示されたエラー

Got an invalid value for 'component' prop for the screen 'hogehoge'. It must be a a valid React Component.

HomeNavigator.js
export default function HomeNavigator() {
  return(
    <Stack.Navigator>
      <Stack.Screen name="Home">
        <HomeScreen />
      </Stack.Screen>
    </Stack.Navigator>
  )
}

上記のようにするとエラーがでる
<HomeScreen />と書かかずに{ () => <HomeScreen /> }関数として渡すようにする

Looks like you're passing an inline function for 'component' prop for the screen 'Home' (e.g. component={() => }). Passing an inline function will cause the component state to be lost on re-render and cause perf issues since it's re-created every render. You can pass the function as children to 'Screen' instead to achieve the desired behaviour.

HomeNavigator.js
export default function HomeNavigator() {
  return(
    <Stack.Navigator>
      <Stack.Screen name="Home" component={() => <HomeScreen />} />
    </Stack.Navigator>
  )
}

componentで関数で渡すようにしても動くには動くけど警告がでる

終わり

React Navigationのgithubのexampleを見たら、最初に書いたような書き方をしたので解決した。React Native関連はまだまだ発展途上でどんどん変わっていくので公式の資料を見るのが一番早い

12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?