每次在react native中打开应用程序时,如何更改背景图像?
我正在尝试用Native应用程序制作应用程序进行练习,并决定添加一些更动态的风格,但我不知道如何实现。
当我试图在后面添加逻辑时,我不断地得到语法错误或导出错误
import React from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TextInput,
Dimensions,
Platform,
ScrollView,
AsyncStorage,
ImageBackground
} from "react-native";
import { AppLoading } from "expo";
import ToDo from "./ToDo";
const { height, width } = Dimensions.get("window");
const noOfPic = 2;
const imgMap = {
0: "img_0.jpg",
1: "img_1.jpg",
2: "img_2.jpg"
};
export default class App extends React.Component {
state = {
newToDo: "",
loadedToDos: false,
toDos: {}
};
componentDidMount = () => {
this._loadedToDos();
};
render() {
const { newToDo, loadedToDos, toDos } = this.state;
console.log(toDos);
if (!loadedToDos) {
return <AppLoading />;
}
return (
<ImageBackground source={require('./assets/images/img_2.jpg')} style={styles.container}>
<StatusBar barStyle="light-content" />
<Text style={styles.title}>MS ToDo App</Text>
<View style={styles.card}>
<TextInput
style={styles.input}
placeholder={"New To Do..."}
value={newToDo}
onChangeText={this._controlNewToDo}
placeholderTextColor={"black"}
returnKeyType={"done"}
autoCorrect={false}
onSubmitEditing={this._addToDo}
underlineColorAndroid={"transparent"}
/>
<ScrollView contentContainerStyle={styles.toDos}>
{Object.values(toDos)
.sort((a, b) => {
return a.createdAt - b.createdAt;
})
.map(toDo => (
<ToDo
key={toDo.id}
deleteToDo={this._deleteToDo}
uncompleteToDo={this._uncompleteToDo}
completeToDo={this._completeToDo}
updateToDo={this._updateToDo}
{...toDo}
/>
))}
</ScrollView>
</View>
</ImageBackground>
);
}
首先让我们将图像映射到对象
const imgMap = {
0: "img_0.jpg",
1: "img_1.jpg",
2: "img_2.jpg",
3: "img_3.jpg",
4: "img_4.jpg"
};
编写一个函数,返回一个基于随机数的图像。每次加载组件/应用程序时,从0-4中随机获得一个数字(因为你有5个图像(
把所有东西放在一起
import React from "react";
import { ImageBackground } from "react-native";
const noOfPic = 4;
const imgMap = {
0: "img_0.jpg",
1: "img_1.jpg",
2: "img_2.jpg",
3: "img_3.jpg",
4: "img_4.jpg"
};
const RandomPic = (props) => {
function getRandomPic() {
const random = Math.floor(Math.random() * Math.floor(noOfPic));
return require(`./images/${imgMap[random]}`);
}
return (
<ImageBackground
source={getRandomPic()}
style={{ height: 500, width: 500 }}
/>
);
};
export default RandomPic;
请确保检查工作中的CodeSandboxhttps://codesandbox.io/s/react-native-random-image-background-md72s?file=/src/RandomPic.js:0-532