LoginSignup
5

More than 5 years have passed since last update.

posted at

React NavigationでNavigationOptionsに関数を埋め込む

React NavigationのnavigationOptionsにクラスメソッドを渡すには少し工夫必要だった。

やりたいこと

やりたいことは以下のようなこと。ただし、navigationOptionsはstaticメソッドなのにthis.handleSaveを渡そうとしても動かない。

  static navigationOptions = ({
    headerLeft: <SaveButton onPress={this.handleSave}/>,
  })

navigationsetParamsして渡す

setParamscomponentDidMountのときに定義し、実行時に渡せればよい。
https://reactnavigation.org/docs/navigators/navigation-prop#setParams-Make-changes-to-route-params

  static navigationOptions = ({
    headerRight: <SaveButton onPress={() => navigation.state.params.handleSave()}/>,
  })

  componentDidMount() {
    this.props.navigation.setParams({
      handleSave: this.handleSave(),
    })
  }

  handleSave = () => {
    // 保存処理
  }

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
What you can do with signing up
5