我正在开发一个托管的 Expo 项目(Expo SDK 版本 49)。我使用
@react-native-community/datetimepicker
显示日期选择器对话框:
import { View } from "react-native";
import RNDateTimePicker from "@react-native-community/datetimepicker";
const DatePickerTest = () => {
const value = new Date();
return (
<View style={{flex: 1}}>
<RNDateTimePicker
mode="date"
value={value}
/>
</View>
);
}
;
export default DatePickerTest;
当我在 Android 上运行代码时,会呈现一个 Date Picker,其标题和选择颜色继承自 Android 的默认主题(在我的例子中为绿色):
我知道,为了更改强调色,我需要更改
styles.xml
中的 android/app/src/main/res/values
(参见例如 https://stackoverflow.com/a/48369871/4350421)。但是,在 Expo 管理的项目中,我无权访问 android
文件夹。
如何在不退出 Expo 的情况下更改强调色?
通过在 SDK 版本 41 中引入配置插件,可以在构建时与 Android 配置文件进行交互,而无需从 Expo 管理的工作流程中退出。请注意,此方法不适用于 Expo Go - 您将需要构建一个自定义开发客户端。
我已经在这里发布了通用方法的详细描述。
要更改强调色:
plugins
目录。custom-android-styles.js
的文件,代码如下:const { withAndroidStyles } = require('@expo/config-plugins');
const withCustomStyles = config => {
return withAndroidStyles(config, async config => {
config.modResults = applyCustomStyles(config.modResults);
return config;
});
};
function applyCustomStyles(styles) {
// Add items to the App Theme
const appTheme = styles.resources.style.find(style => style.$.name === 'AppTheme');
if (appTheme) {
appTheme.item.push({ _: '@style/Dialog.Theme', $: { name: 'android:datePickerDialogTheme' } });
appTheme.item.push({ _: '@style/Dialog.Theme', $: { name: 'android:timePickerDialogTheme' } });
}
// Add new style definition
styles.resources.style.push({
$: { name: 'Dialog.Theme', parent: 'Theme.AppCompat.Light.Dialog' },
item: [{ _: '#a7243a', $: { name: 'colorAccent' } }],
});
return styles;
}
module.exports = withCustomStyles;
app.config.js
:export default {
expo: {
//...
plugins: [
//...
"./plugins/custom-android-styles.js",
]
}
};
如果一切顺利,你的 DatePicker 将如下所示: