アプリのヘッダーにある「保存」ボタンにコンポーネントの値を渡したいときどうするか、みたいな話です
処理の概要
- コンポーネントの中で
setParams
する -
setParam
に渡したい値を入れる -
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')
})} />
)
})