LoginSignup
1
0

More than 3 years have passed since last update.

navigationOptionsにコンポーネントのpropsを渡したい

Last updated at Posted at 2019-12-30

アプリのヘッダーにある「保存」ボタンにコンポーネントの値を渡したいときどうするか、みたいな話です

処理の概要

  1. コンポーネントの中で setParams する
  2. setParamに渡したい値を入れる
  3. navigationOptionsの中でgetParamする

サンプルコード


// 画面
const FooScreen: React.FC & NavigationStackScreenComponent = ({ navigation }) => {
  // navigationでこの値を渡したい
  const [count, setCount] = useState<number>(0)

  // countが更新されたらnavigationのparamの値も更新する
  useEffect(() => {
    navigation.setParams({ fooParam: count })
  }, [count])

  return (
    <View>
      <Button title='おしてね' onPress={() => setCount(count + 1)} />
    </View>
  )
}

// navigation options
FooScreen.navigationOptions = ({ navigation }) => ({
  title: 'ふーーー',
  headerRight: (
    <Button title='保存' onPress={() => navigation.navigate('Bar', {
      // setParamで設定した値を取得 -> Bar画面へのparamに入れ直す
      fooParam: navigation.getParam('fooParam') 
    })} />
  )
})
1
0
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
1
0