如何在 react-native 中设置 Alert 元素的样式?

IT技术 reactjs react-native
2021-03-30 05:59:10

我正在使用 react-native 并创建了一个 Alert 元素。

Alert.alert(
    'Warning',
    'bla bla bla',
    [
           {text: 'OK', onPress: () => console.log('OK Pressed')},
    ]
)

现在我想对它应用一些样式。假设我想为文本应用红色背景颜色和白色。

我怎样才能做到这一点?是否可以?

4个回答

实际上有一种方法可以自定义按钮上的文本,但您仅限于提供的内容......下面是来自 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}
    )
我认为这仅适用于RN 文档中指定的 iOS
2021-05-29 05:59:10
样式:“破坏性”是我需要将取消按钮颜色更改为红色。
2021-06-05 05:59:10

您可以使用像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

莫代尔不警觉。
2021-06-09 05:59:10
我如何定义这样的通用模态,并在任何地方使用
2021-06-19 05:59:10

我认为这是不可能的,因为Alertreact-native组件是包含在 Android 和 iOS 中的东西,不能修改:/

在这里推荐这种类似的问题

拜拜 !

我一直在 android/rn 资源中寻找这个。

纵观执行代码,它实例化AlertDialog.Builder,并着眼于原始的Android源代码AlertDialog.Builder,只有上下文的构造采用了resolveDialogThemethemeResId=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。