我正在玩React Native,以构建一个非常基本,简单的应用程序。
我有一个JSON
文件,其中包含人们应该完成的一些任务。我从选项数组中随机选择一项任务,并显示文本和类型。任务具有类型,并且它们是实际任务的短文本,例如:
{
"text": "Open Wikipedia and read a random article.",
"type": "Knowledge"
},
我还想做的是更改显示的背景图像的类型,以使其适合每个任务的类型。由于我将图像用作文本后面的背景放置,因此必须更改source
图像的一部分。
似乎我不能只是将task.type.toLowerCase();
或变量粘贴taskStyle
到<Image source>
(将是<Image source={require('image!{taskStyle}'}
。
以同样的方式,我想将相同的变量移交taskStyle
给现在<View>
固定为的标签,因为每种类型的任务也应该有不同的颜色。backgroundColor
style
由于我对React知之甚少,因此我很确定我没有一个非常基本的概念,所以我不知道如何正确处理。有人可以指出我这样做的正确方法吗?任何帮助,将不胜感激 :)
这是iOS部分的完整代码:
'use strict';
var React = require('react-native');
var Tasks = require('./data/tasks.json');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
StatusBarIOS,
} = React;
var progress = React.createClass({
render: function() {
StatusBarIOS.setStyle(1);
var randomTask = Math.floor(Tasks.length * Math.random());
var task = Tasks[randomTask];
var taskStyle = task.type.toLowerCase();
return (
<Image
style={styles.container}
source={require('image!mind')}
>
<View style={[
styles.textWrapper,
{
backgroundColor: 'rgba(11,136,191,0.7)',
}
]}>
<Text
style={[
styles.category,
styles.text,
]}
>
{task.type}
</Text>
<Text
style={[
styles.task,
styles.text,
]}
>
{task.text}
</Text>
</View>
</Image>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
resizeMode: 'cover',
// setting these to null avoids too huge images
width: null,
height: null,
},
textWrapper: {
alignItems: 'center',
backgroundColor: 'transparent',
flex: 1,
justifyContent: 'center',
padding: 20,
},
knowledge: {
backgroundColor: 'rgba(240,200,46,0.8)',
},
text: {
backgroundColor: 'transparent',
fontFamily: 'Avenir',
margin: 10,
textAlign: 'center',
},
category: {
color: 'rgba(255,255,255,0.7)',
fontSize: 24,
},
task: {
color: '#FFFFFF',
fontSize: 36,
},
});
AppRegistry.registerComponent('progress', () => progress);
太太,先生。
尽管我还没有摆弄React的“本机”版本,但是,对于如何解决这个问题,我有两个自发的想法。
I.将图像保留在内置的应用程序中
如果知道要处理的主题/图像的数量,则可以简单地全部要求它们,并将它们存储在其属性名称反映主题名称的对象中。
var imgTopic1 = require('image!topic1');
var imgTopic2 = require('image!topic2');
…
var topicImages = {
topic1: imgTopic1,
topic2: imgTopic2,
…
};
return (<Image src={topicImages[topic]} … />);
二。使用外部资源
如果您希望能够添加更多主题/图像而不必发布应用程序的升级,则可以使用外部图像服务并从该主题构造URL。
var imgServiceRoot = 'http://example.com/images/';
var imgUrl = imgServiceRoot + topic + '.jpg';
return (<Image src={{uri: topicImages[topic]}} … />);
我忘了什么吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句