React native 集成 Mobx
store:
import { observable, action } from 'mobx' class Auth { @observable status = 'init status'; @action.bound login() { this.status = 'login'; } @action.bound logout() { this.status = 'logout'; } } const auth = new Auth(); export default auth;
通过 Provider
可以在多个组件中注入 store,尤其是引入了 react-navigation,无法显式地通过 props 传递 store。
import React, {Component} from 'react' import { AppRegistry } from 'react-native'; import App from './src/App'; import auth from './src/stores/auth' import { Provider, observer } from 'mobx-react' @observer class Firefly extends Component { render() { return ( <Provider auth={auth}> <App/> </Provider> ); } } AppRegistry.registerComponent('firefly', () => Firefly);
HomeScreen:
import React, { Component } from 'react' import { View, Text, Button, } from 'react-native' import { observer, inject } from 'mobx-react' @inject('auth') @observer class HomeScreen extends Component { static navigationOptions = { title: 'Welcome', headerStyle: { backgroundColor: '#fff', elevation: 0, }, style: { borderColor: '#fff' }, }; render() { return ( <View> <Text>{ this.props.auth.status }</Text> <Button title="login" onPress={ this.props.auth.login }/> <Button title="logout" onPress={ this.props.auth.logout }/> </View> ) } } export default HomeScreen;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论