0
0

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.

ReactNative propsを利用せずに別クラスから別クラスに値を渡す方法

Posted at

React Native Event Listeners

# 用途

別クラスから別クラスに値を渡す際に使用

なぜ使用したかったか?

  • Aクラスで使用していた変数をBクラスでも使用したい
  • 変数1つのためだけに、コンポーネントを呼び出すことはしたくない

使用例

  • ボタンを押したら no dataのテキストをit worksに変える処理
import { EventRegister } from 'react-native-event-listeners'

/*
 * RECEIVER COMPONENT
 */
class Receiver extends PureComponent {
    constructor(props) {
        super(props)
        
        this.state = {
            data: 'no data',
        }
    }
    
    componentWillMount() {
        this.listener = EventRegister.addEventListener('myCustomEvent', (data) => {
            this.setState({
                data,
            })
        })
    }
    
    componentWillUnmount() {
        EventRegister.removeEventListener(this.listener)
    }
    
    render() {
        return <Text>{this.state.data}</Text>
    }
}

/*
 * SENDER COMPONENT
 */
const Sender = (props) => (
    <TouchableHighlight
        onPress={() => {
            EventRegister.emit('myCustomEvent', 'it works!!!')
        })
    ><Text>Send Event</Text></TouchableHighlight>
)

まとめ

  • EventRegister.emit()と、EventRegister.addEventListener()セットの関係
  • 関数の第一引数はemitとaddEventListennerを繋ぐuniqキー,第二引数はemit→addEventListennerに渡すデータ
  • addEventListennerを呼び出した後はremoveEventListennerを呼び出して消す?

参考

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?