我正在使用 react-native 并创建了一个 Alert 元素。
Alert.alert(
'Warning',
'bla bla bla',
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
]
)
现在我想对它应用一些样式。假设我想为文本应用红色背景颜色和白色。
我怎样才能做到这一点?是否可以?
我正在使用 react-native 并创建了一个 Alert 元素。
Alert.alert(
'Warning',
'bla bla bla',
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
]
)
现在我想对它应用一些样式。假设我想为文本应用红色背景颜色和白色。
我怎样才能做到这一点?是否可以?
实际上有一种方法可以自定义按钮上的文本,但您仅限于提供的内容......下面是来自 react native 的类型定义。然后是一个显示红色按钮的简单示例。基本上“默认”是蓝色,“取消”是粗体但仍然是蓝色,“破坏性”是红色。
**
* An Alert button style
*/
export type AlertButtonStyle = $Enum<{
/**
* Default button style
*/
'default': string,
/**
* Cancel button style
*/
'cancel': string,
/**
* Destructive button style
*/
'destructive': string,
}>;
Alert.alert("Look out!",
"Hitting reset will wipe all the app's data on your phone. This cannot be undone!",
[
{text: 'Reset', onPress: this._doSomethingSerious, style: 'destructive'},
{text: 'Cancel'},
],
{cancelable: false}
)
您可以使用像react-native-modalbox这样的自定义库。
您将能够根据需要设置模态样式:
<Modal style={{background: 'red'}} ref={"modal1"}>
<Text style={{color: 'white'}}>Basic modal</Text>
<Button onPress={this.toggleSwipeToClose} style={styles.btn}>Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})</Button>
</Modal>
您可以使用打开模态
openModal1(id) {
this.refs.modal1.open();
}
查看示例以查看更多选项。
奖励:如果你想为 react-native 找到一个好的库,试试js.coach
我一直在 android/rn 资源中寻找这个。
纵观执行代码,它实例化AlertDialog.Builder,并着眼于原始的Android源代码的AlertDialog.Builder,只有上下文的构造采用了resolveDialogTheme带themeResId=0。不管怎样,这个方法的重要部分是这样的:
} else {
final TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.alertDialogTheme, outValue, true);
return outValue.resourceId;
}
后备样式/主题是alertDialogTheme,因此您可以android:alertDialogTheme像这样覆盖警报对话框的默认主题:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:alertDialogTheme">@style/ThemeAlert</item>
</style>
<style name="ThemeAlert" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- This one changes buttons text color -->
<item name="colorAccent">#152849</item>
</style>
</resources>
我需要更改默认按钮的文本,所以这对我有用(至少在 RN 0.61.5 上),但我不确定可以更改哪些props。
当然,这并不能解决运行时更改颜色的问题……如果确实需要这样做,您可能应该使用 lib 或自己编写本机module。