LoginSignup
5
3

More than 5 years have passed since last update.

ReactNavigationのTabNavigatorで切替時に毎回イベントさせる方法

Last updated at Posted at 2018-05-11

v2

import React from 'react'
import { createBottomTabNavigator } from 'react-navigation'
import { View, Text } from 'react-native'

class Home extends React.Component {
  componentDidMount() {
    this.subs = [
      this.props.navigation.addListener('didFocus', () => this._onFocus())
    ]
  }

  componentWillUnmount() {
    this.subs.forEach(sub => sub.remove())
  }

  _onFocus = () => {
    console.log('home on focus')
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Home!</Text>
      </View>
    )
  }
}

class Test extends React.Component {
  componentDidMount() {
    this.subs = [
      this.props.navigation.addListener('didFocus', () => this._onFocus())
    ]
  }

  componentWillUnmount() {
    this.subs.forEach(sub => sub.remove())
  }

  _onFocus = () => {
    console.log('test on focus')
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>Test!</Text>
      </View>
    )
  }
}

export default createBottomTabNavigator(
  {
    Home,
    Test
  }
)

v1


  static navigationOptions = ({ navigation }) => {
    return {
      tabBarOnPress: ({ scene: { index }, jumpToIndex }) => {
        jumpToIndex(index)
        navigation.state.params.onFocus()
      }
    }
  }

  componentDidMount() {
    this.props.navigation.setParams({
      onFocus: this._onFocus.bind(this)
    })
  }

  _onFocus = () => {
    // do something
  }
5
3
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
5
3