如何为React Native的LinearGradient设置外部渐变颜色和样式?

woobm2wo  于 2023-06-06  发布在  React
关注(0)|答案(2)|浏览(223)

“react-native-linear-gradient”如何将颜色作为 prop 和样式传递

interface Props {
        // gradientColors:string[]
    gradientColors:Array<string>
}

const BaseButton: React.FC<Props> = ({ gradientStyle ,gradientColors}) => {

 const styles = buttonStyle({
 btnHeight,btnWidth, btnColor, btnFont, btnTextColor, btnBorderRadius,
    })
    const gradientColorsTest = ['#4c669f', '#3b5998', '#192f6a']

    return (
        <LinearGradient
            // colors={['#4c669f', '#3b5998', '#192f6a']}
            colors={gradientColors}
            // style={styles.gradient}
            style={gradientStyle}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}>

            <TouchableOpacity onPress={()=>{}}>
                <View style={styles.buttonViewStyle}>
                    <Text>ButtonTest</Text>
                </View>
            </TouchableOpacity>
        </LinearGradient>
    )}
export default BaseButton

如何将颜色和样式发送到外部以实现线性渐变。
我尝试以colors={gradientColors}的形式传递,但显示错误“****无法读取未定义的属性“map”****如何解决此错误

63lcw9qa

63lcw9qa1#

react-native-linear-gradient用于设置外部渐变颜色

this is not suitable for in Typescript: gradientColors: string[];

 correct format is : gradientColors: (string | number)[];
  • react-native-linear-gradient颜色类型为:(string)|编号)[]*

此类型仅在typescript中被接受

hmtdttj4

hmtdttj42#

这样调用BaseButton组件:

<BaseButton
    gradientColors: {['#4c669f', '#3b5998', '#192f6a']}
    gradientStyle: {{flex: 1}} 
>

</BaseButton>

BaseButton组件中,将props传递给LinearGradient

import { StyleProp, TouchableOpacity, View, ViewStyle, Text } from 'react-native';

interface Props {
    gradientColors: (string | number)[];
    gradientStyle: StyleProp<ViewStyle>;
}

const BaseButton: React.FC<Props> = (props) => {
const styles = buttonStyle({btnHeight,btnWidth, btnColor, btnFont, btnTextColor, btnBorderRadius})

return (
        <LinearGradient
            colors={props.gradientColors}
            style={props.gradientStyle}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}>
            <TouchableOpacity onPress={()=>{}}>
                <View style={styles.buttonViewStyle}>
                    <Text>ButtonTest</Text>
                </View>
            </TouchableOpacity>
        </LinearGradient>
    )
}

相关问题