如何在 React-native 中制作线性渐变背景

How to make linear-gradient background in React-native

如何在内部创建渐变

<View />

https://github.com/react-native-community/react-native-linear-gradient

尝试以下步骤:

1) 从 react-native-linear-gradient 库导入 LinearGradient

import LinearGradient from 'react-native-linear-gradient';

2) 将一些弹性值设置为 LinearGradient

<LinearGradient
    colors={['#33ccff', '#ff99cc']}
    style={{ flex:1 }}
>
    <View>
        //set your content or elements here
    </View>
</LinearGradient>

您可以使用 LinearGradient 而不是 View 并将您的内容放在那里。

  <LinearGradient
    colors={['#373B44', '#4286f4', '#373B44']}
    style={{
      flex: 1,
    }}
  >
    <Text>
      Test
    </Text>
  </LinearGradient>

但您也可以使用 View 作为 LinearGradient 中的内容。

  <LinearGradient
    colors={['#373B44', '#4286f4', '#373B44']}
    style={{
      flex: 1,
    }}
  >
    <View
      style={{
        margin: 20,
      }}
    >
      <Text>
        Test
      </Text>
    </View>
  </LinearGradient>

我还用源代码解释了 react-native-linear-gradient 的用法及其功能 here

如果您使用的是 expo, 我创建了一个单独的组件

您可以在任何组件中导入并使用它

import { fonts } from '@src/theme/typography'
import { LinearGradient } from 'expo-linear-gradient'
import React from 'react'
import { ViewStyle, StyleProp, StyleSheet, Text } from 'react-native'


const Button = (props) => {
    const { style, text } = props
    return(
        <LinearGradient 
        colors={['#ffa700', '#ff9300']}
        style={[styles.container, style]}>
        <Text style={styles.text}>
        {text}
        </Text>
        </LinearGradient>
    )
}

const styles = StyleSheet.create({
    container: {
        height: 48,
        borderRadius: 8
    },
    text: {
        textAlign: 'center',
        marginTop: 'auto',
        marginBottom: 'auto',
        color: '#fefffe',
        fontSize: 18,
        fontFamily: fonts.medium,

    }
})

export default Button