使用 PlatformColor 和响应主题
需要进行架构审查:本文档旨在支持针对 React Native 的“旧”或“遗留”架构的开发。它可能适用也可能不适用于新架构的开发,需要审查并可能需要更新。有关 React Native Windows 中 React Native 架构的信息,请参阅新旧架构。
概述
Windows 支持两种独特的原生样式/主题行为:一是深色和浅色主题更改,二是自适应画笔和系统颜色。本文将向您展示如何设置您的应用程序以监听主题更改,并根据需要使用 Windows 画笔。
设置和处理主题更改事件
在此示例中,我们将探讨三件事:
- 如何设置您的 React Native 应用程序,使其对系统主题的样式和事件敏感
- 主题更改发生时如何切换样式
- 处理主题更改事件
使用钩子(hooks)对主题更改敏感
首先将 useColorScheme
钩子导入到您的 React Native 应用程序中。
import { useColorScheme } from 'react-native'
const MyAppComponent = () => {
const colorScheme = useColorScheme();
return (
<Button title='click me' color={colorScheme === 'dark' ? 'grey' : 'orange'}/>
);
};
注意:当远程调试时,
useColorScheme()
将始终返回 'light'。
无需钩子即可设置您的应用程序对主题更改敏感
首先将 Appearance
API 导入到您的 React Native 应用程序中。
import { Appearance } from 'react-native'
创建一个局部变量以用于样式条件或在其他地方引用,然后提供挂载函数以确保您正确监听主题更改事件。
class MyAppClass extends Component {
state = {
currentTheme: Appearance.getColorScheme()
};
componentDidMount() {
Appearance.addChangeListener(this.onAppThemeChanged);
};
componentWillUnmount() {
Appearance.addChangeListener(this.onAppThemeChanged);
};
onAppThemeChanged = (theme) => {
const currentTheme = theme;
this.setState({currentTheme});
};
render() {
<Button title='click me' color={this.state.currentTheme === 'dark' ? 'grey' : 'orange'}/>
}
}
注意:当远程调试时,
getColorScheme()
将始终返回 'light'。
使用 Windows 定义的主题画笔
以下示例介绍了如何访问和使用 Windows 系统主题画笔并将其应用于样式。有关 Windows XAML 主题资源的更多信息,请参阅:https://docs.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-theme-resources
您应用程序原生 ResourceDictionary
中的任何画笔/颜色值,无论是来自系统还是自定义原生资源,都可以使用 PlatformColor
进行访问。
在样式中使用主题画笔
const styles = StyleSheet.create({
title: {
fontSize: 19,
fontWeight: 'bold',
color: PlatformColor('SystemControlPageTextBaseHighBrush')
},
});
应用系统强调色变体
在 Windows 中,有算法生成的强调色——被称为浅色或深色 1、2 和 3。此示例介绍了使用 windowsbrush
对象应用它的效果。
const styles = StyleSheet.create({
title: {
fontSize: 19,
fontWeight: 'bold',
color: PlatformColor('SystemAccentColorLight3')
},
});
注意:系统强调色在原生层是 Color
对象,而其他示例展示的主题画笔是 SolidColorBrush
对象。这意味着 SolidColorBrushes
将根据主题(浅色、深色或高对比度)自动调整,而 Colors
将保持静态。
PlatformColor
访问 Reveal 和 Acrylic
使用 在支持 Reveal 和 Acrylic 功能的 Windows 设备上,PlatformColor
API 通过 JavaScript 提供对它们的访问。
使用系统 Acrylic
PlatformColor
API 允许您访问所有系统 Acrylic 画笔,这些画笔可以通过资源名称访问。只需在组件的样式中提供资源画笔名称字符串,它就会相应地应用。
const styles = StyleSheet.create({
viewcomponent: {
backgroundColor: PlatformColor('SystemControlAcrylicWindowBrush')
},
});
应用 Reveal 突出显示
Reveal 可以像 Acrylic 和其他系统画笔一样应用于表面。
const styles = StyleSheet.create({
viewcomponent: {
backgroundColor: PlatformColor('SystemControlBackgroundAccentRevealBorderBrush')
},
});