反应原生中的线性渐变背景色



在我的应用程序中,我需要动态更改背景颜色。更改通过回调从子视图到父视图。 目前它看起来像这样:

儿童视图:

onButton1Press() {
this.props.callbackFromParent('#ff4c00');
}

父视图:

myCallback = (dataFromChild) => {
this.setState({ backgroundColor: dataFromChild }); 
}

它工作得很好,但问题是我需要实现线性渐变背景颜色。

我找到了一个"反应原生线性渐变"库,它适用于其他视图,如按钮,但我无法将其设置为背景颜色。

例:

<LinearGradient colors={['#085d87', '#27c7bb']}
start={{ x: 0, y: 1 }}
end={{ x: 1, y: 0 }}>
<Text style={styles.buttonText}>LinearGradient</Text>
</LinearGradient>

可以将背景颜色设置为渐变吗?有没有另一种方法可以在反应原生中实现?谢谢。

如果你想把它放在后台,那么你只需要用你的view包裹<LinearGradient作为背景 例:

<View style={{flex:1}}>
<LinearGradient color={[...]} style={{flex:1}}>
...//Your component
</LinearGradient>
</View> 

希望这有帮助!

您可以创建自定义类或组件,并在按下子组件上的按钮时使用它来更改父视图。

示例代码:

import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class Gradient extends Component {
render() {
const  gradientHeight=500;
const gradientBackground  = 'purple';
const data = Array.from({ length: gradientHeight });
return (
<View style={{flex:1,justifyContent:'center'}}>
{data.map((_, i) => (
<View
key={i}
style={{
position: 'absolute',
backgroundColor: gradientBackground,
height: 1,
bottom: (gradientHeight - i),
right: 0,
left: 0,
zIndex: 2,
opacity: (1 / gradientHeight) * (i + 1)
}}
/>
))}
<Text style{{textAlign:'center',alignSelf:'center',fontSize:25}}>Hello</Text>
</View>
);
}
}

世博会有LinearGradient,这很容易。

import { LinearGradient } from 'expo';
<LinearGradient
colors={['#4c669f', '#3b5998', '#192f6a']}
style={{ padding: 15, alignItems: 'center', borderRadius: 5 }}>
<Text
style={{
backgroundColor: 'transparent',
fontSize: 15,
color: '#fff',
}}>
Sign in with Facebook
</Text>
</LinearGradient>

最新更新