了解如何在 React Native 应用中设置按钮样式。
React Native 导出一个 <Button>
组件,该组件公开 Android、iOS 和 Web 的原生按钮元素。此组件接受 title
和 onPress
属性。它不接受 style
属性并且不支持自定义样式。
¥React Native exports a <Button>
component that exposes the native button element for Android, iOS, and the web. This component accepts title
and onPress
props. It does not accept a style
prop and doesn't support custom styling.
最接近从 React Native 导出的 <Button>
样式的是使用 color
属性。以下是 Android、iOS 和 Web 上的两个按钮的示例。
¥The closest you can get to styling a <Button>
exported from React Native is with the color
prop. Below is an example of two buttons on Android, iOS, and the web.
第一个按钮是默认的 <Button>
,第二个按钮是另一个默认的 <Button>
,其 color
属性设置为 "red"
。
¥The first button is the default <Button>
and the second is another default <Button>
with its color
prop set to "red"
.
要创建具有自定义样式的按钮,你可以使用 <Pressable>
组件。<Pressable>
除了允许我们自定义其行为之外,还允许我们完全自定义可按下元素(如按钮)的外观。
¥To create a button with a custom style, you can turn to the <Pressable>
component.
<Pressable>
lets us fully customize the appearance of a pressable element (like a button), in addition to allowing us to customize its behavior.
下面是使用 <Pressable>
创建按钮组件的示例:
¥Here's an example of using <Pressable>
to create a button component:
import React from 'react';
import { Text, StyleSheet, Pressable } from 'react-native';
export default function Button(props) {
const { onPress, title = 'Save' } = props;
return (
<Pressable style={styles.button} onPress={onPress}>
<Text style={styles.text}>{title}</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'black',
},
text: {
fontSize: 16,
lineHeight: 21,
fontWeight: 'bold',
letterSpacing: 0.25,
color: 'white',
},
});
这是这段代码的结果:
¥And here's the result of this code:
React Native 的 <Button>
组件不接受 style
属性,其 color
属性受到限制,并且在 Android、iOS 和 Web 上的显示方式有所不同。使用 <Pressable>
组件,我们可以创建适合我们应用设计的自定义按钮。这些样式在 Android、iOS 和 Web 上也将是相同的,这将使我们的应用在每个平台上具有一致的外观。
¥React Native's <Button>
component does not accept a style
prop, and its color
prop is limited and appears differently across Android, iOS, and the web. With the <Pressable>
component, we can create custom buttons that fit our app's design. Those styles will also be the same across Android, iOS, and the web, which will give our apps a consistent look on every platform.