如何循环和呈现元素在本地反应?

是否可以在渲染函数中循环一个相同的组件?

就像这样:

...


onPress = () => {
...
};


initialArr = [["blue","text1"],["red","text2"]];
buttonsListArr = [];


for (let i = 0; i < initialArr.length; i++)
{
buttonsListArr.push(
<Button style={{borderColor:{initialArr[i][0]}}} onPress={this.onPress.bind(this)}>{initialArr[i][1]}</Button>
);
}


...


render() {
return (
<View style={...}>
{buttonsListArr}
</View>
)};

我的意思是这只是一个有限的组件列表,所以像 ListView/ScrollView 等这样的组件在这种情况下是不适用的。这只是句法问题。

150061 次浏览

You would usually use map for that kind of thing.

buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);

(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)

As a side, I would use an object instead of an array. I find it looks nicer:

initialArr = [
{
id: 1,
color: "blue",
text: "text1"
},
{
id: 2,
color: "red",
text: "text2"
},
];


buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);
render() {
return (
<View style={...}>
{initialArr.map((prop, key) => {
return (
<Button style=\{\{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
);
})}
</View>
)
}

should do the trick

For initial array, better use object instead of array, as then you won't be worrying about the indexes and it will be much more clear what is what:

const initialArr = [{
color: "blue",
text: "text1"
}, {
color: "red",
text: "text2"
}];

For actual mapping, use JS Array map instead of for loop - for loop should be used in cases when there's no actual array defined, like displaying something a certain number of times:

onPress = () => {
...
};


renderButtons() {
return initialArr.map((item) => {
return (
<Button
style=\{\{ borderColor: item.color }}
onPress={this.onPress}
>
{item.text}
</Button>
);
});
}


...


render() {
return (
<View style={...}>
{
this.renderButtons()
}
</View>
)
}

I moved the mapping to separate function outside of render method for more readable code. There are many other ways to loop through list of elements in react native, and which way you'll use depends on what do you need to do. Most of these ways are covered in this article about React JSX loops, and although it's using React examples, everything from it can be used in React Native. Please check it out if you're interested in this topic!

Also, not on the topic on the looping, but as you're already using the array syntax for defining the onPress function, there's no need to bind it again. This, again, applies only if the function is defined using this syntax within the component, as the arrow syntax auto binds the function.

If u want a direct/ quick away, without assing to variables:

{
urArray.map((prop, key) => {
console.log(emp);
return <Picker.Item label={emp.Name} value={emp.id} />;
})
}