React Native createContext 实现全局退出登录
这里使用React 的勾子,实现全局参数 createContext ,这样就不用每个页面都去获取props ,这样太麻烦了,这里是跨页面的例子
创建一个通用的文件contentmanager.js
import React from 'react' export const MyContext = React.createContext();
主文件引用 Test22.js
import React, { useContext, useState,useReducer,useMemo } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import SonButton from './SonButton';
import {MyContext} from './contentmanager'
import { Button } from '@rneui/base';
//全局文本
export default function Test22 () {
//父组件
const [theme,setTheme] = useState('yellow1')
const [state, dispatch] = useReducer(reducer,
{age : 42,name:'szy', isloading:false,isLogin:true})
//定义一个方法
const authContext = useMemo(()=>({
addAge: async(data)=> { dispatch({ type: 'add_age' }) },
removeAge:async(data)=> { dispatch({ type: 'remove_age' }) },
logout:async(data)=> {
console.log('用户点击了退出data')
dispatch({ type: 'logout' })
}
}),[])
return (
<MyContext.Provider value={{theme,setTheme,authContext}}>
{state.isLogin ?
<View style={{flexDirection:'row'}}>
<View style={{backgroundColor:'#fff',height:200,width:100}}>
<Text> 这里测试context的作用方法当前主题是:{theme}</Text>
<Text>Hello:{state.age}-----name:{state.name}</Text>
</View>
<View>
<MTButton/>
</View>
</View>
:
<View style={{backgroundColor:'#fff',height:200,width:100}}>
<Text> 这里测试context的作用方法当前主题是:{theme}</Text>
<Text>您已退出登录 --- name:{state.name}</Text>
</View>
}
</MyContext.Provider>
)
function reducer(state, action) {
if (action.type === 'add_age') {
return {
isLogin: true,
age: state.age + 1,
name:'szy'
};
}else if(action.type === 'remove_age'){
return {
isLogin: true,
age: state.age - 1,
name:'szy'
};
}else if(action.type === 'logout'){
return {
age: 0,
isLogin: false,
name:'已经退出'
};
}
throw Error('Unknown action.');
}
}
function MTButton(){
const {theme,setTheme,authContext} = useContext(MyContext);
//子组件
return (
<View style={{backgroundColor:'red',height:100,width:100,flexWrap:'wrap'}}>
<View >
<Text>这里是子组件 {theme}</Text>
<Text>这里是MTButton</Text>
<Button title={'点击更换皮肤' } onPress={()=> setTheme("black")}/>
<Button title={'增加年龄' } onPress={()=> authContext.addAge()}/>
<Button title={'减少年龄' } onPress={()=> authContext.removeAge()}/>
</View>
<View>
<SonButton/>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
},
});
子页面SonButton.js
import React, { Component,useContext } from 'react'
import { Text, StyleSheet, View,Button } from 'react-native'
import {MyContext} from './contentmanager'
export default function SonButton (){
const {theme,setTheme,authContext} = useContext(MyContext);
//在这实现参数穿透,子组件改变顶部的全局的参数
return (
<View style={{backgroundColor:'green',height:100,width:100}}>
<Text>这里是Son组件 {theme}</Text>
<Text>这里是SonButton</Text>
<Button title={'退出' } onPress={()=> authContext.logout()}/>
</View>
)
}
const styles = StyleSheet.create({})
效果是子页面点击退出登录,调用主页面方法,并且主页面会进行渲染
点击退出登录 
浙公网安备 33010602011771号