美文网首页ReactNative Hooks
RN-切换主题-简洁版

RN-切换主题-简洁版

作者: 精神病患者link常 | 来源:发表于2021-04-21 18:27 被阅读0次

    实现功能:切换背景色

    使用技术点:context

    1. 声明context

    import {createContext} from 'react'
    
    export const ThemesContent = createContext({
      color:'', // 颜色
      changeColor:()=>{} // 修改颜色
    })
    

    2.程序入口使用

    function StackNavigator() {
      // 默认背景色
      const [themesColor, setThemesColor] = useState('red')
      return <ThemesContent.Provider value={{
        color:themesColor,
        changeColor:(color)=>{
          // 修改背景色
          setThemesColor(color)
        }
      }}>
        <Stack.Navigator>
          <Stack.Screen name={'TransitionalPage'} component={TransitionalPage}/>
          <Stack.Screen name={'TabNavigator'} component={TabNavigator}/>
          <Stack.Screen name={'Login'} component={Login}/>
          {RenderRoutes()}
        </Stack.Navigator>
      </ThemesContent.Provider>
    }
    

    3.页面内部使用

    import { ThemesContent } from '../../common/Themes'
    
    const themesContent = React.useContext(ThemesContent)
    <View style={[styles.mainView,{backgroundColor:themesContent.color}]}>
      <TouchableOpacity onPress={()=>{
            // 修改主题背景色
            themesContent.changeColor('blue')
          }}>
            <Text>点击修改主题背景色</Text>
          </TouchableOpacity>
    ...
    

    相关文章

      网友评论

        本文标题:RN-切换主题-简洁版

        本文链接:https://www.haomeiwen.com/subject/jnyzlltx.html