我在渲染块内运行了 forEach,它在渲染块上正常输出
控制台,但文本标签未显示在输出中。
问题是什么?
import React from "react";
import { StyleSheet, Text, View } from "react-native";
class Lotto extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 6,
maxNum: 45
};
this.lottoSet = this.createLottoNumber();
}
createLottoNumber() {
let lottoSet = new Set();
let rNum;
for (let i = 0; i < this.state.count; i++) {
rNum = Math.round(Math.random() * (this.state.maxNum * 1) + 1);
if (lottoSet.has(rNum)) i--;
else lottoSet.add(rNum);
}
return lottoSet;
}
render() {
return (
<View style={styles.container}>
{this.lottoSet.forEach(n => {
console.log(`<Text style={styles.item}>${n.toString()}</Text>`);
return <Text style={styles.item}>{n.toString()}</Text>;
})}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#333",
flexDirection: "row",
paddingTop: "10%",
justifyContent: "center"
},
item: {
color: "#fff",
textAlign: "center",
width: "100px"
}
});
export default Lotto;
最佳答案
您必须使用 map 来渲染元素。
render() {
return (
<View style={styles.container}>
{this.lottoSet.map(n => (
<Text key={n.toString()} style={styles.item}>{n.toString()}</Text>
))}
</View>
);
}
React 是声明式的,需要声明 View 状态来渲染,map 将构建一个声明的、不可变的 View 状态。而使用 forEach 有可能在渲染方法之外产生副作用,因此不受支持。
关于react-native - react 原生渲染 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60735050/