如何在 React-native 中循环和渲染元素? [英] How to loop and render elements in React-native?

查看:126
本文介绍了如何在 React-native 中循环和渲染元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Render 函数中循环相同的组件?

Is it possible to loop an identical component in Render function?

像这样:

...

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 等任何组件都不适用于这种特殊情况.这只是语法问题.

I mean this is just finite list of components, so any components like ListView/ScrollView etc is not applicable in this particular case. This is just syntax question.

推荐答案

你通常会使用 map 来处理这种事情.

You would usually use map for that kind of thing.

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

(每当你在 React 中做映射时,key 是一个必要的 prop.key 需要是生成组件的唯一标识符)

另一方面,我会使用对象而不是数组.我觉得它更好看:

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>
);

这篇关于如何在 React-native 中循环和渲染元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆