简体   繁体   English

React Native:在 map 中传递不同的 styles

[英]React Native: pass different styles in a map

I want to have 4 boxes, each box with a different color, and I want to do that loading each style from map().我想要 4 个盒子,每个盒子都有不同的颜色,我想从 map() 加载每种样式。 The below code doesn't compile, I wrote it so you understand what I'm trying to do.下面的代码无法编译,我写了它是为了让你明白我想要做什么。 The error derives from inside the View at styles.{box.name}, I want instead of {box.name} to put array's elements so the function can take Stylesheet's props.该错误来自 styles.{box.name} 的视图内部,我想代替 {box.name} 放置数组的元素,以便 function 可以采用样式表的道具。

export default function Imagesfun() {
    const array = [{
        name: "box1",
    },
    {
        name: "box2",
    },
    {
        name: "box3",
    },
    {
        name: "box4",

    },
    {
        name: "box5",
    }]
    return (
        <View style={styles.container}>

            {array.map(box => <Text style={styles.{box.name}} key={box.name}>{box.name}</Text>)}

        </View >
    )
}

const styles = StyleSheet.create({
    container: {
        justifyContent: "space-around",
        alignContent: "center",
        backgroundColor: 'black',
    },
    box1: {
        backgroundColor: 'lightblue',
    },
    box2: {
        backgroundColor: 'lightred',
    },
    box3: {
        backgroundColor: 'lightyellow',

    },
    box4: {
        backgroundColor: 'lightpurple',

    },
    box5: {
        backgroundColor: 'lightgreen',
    },
});

Change {styles.{box.name}} to {styles[box.name]} .{styles.{box.name}}更改为{styles[box.name]} Check this Q & A for more details.查看此问答以获取更多详细信息。

Try as following:尝试如下:

<View style={styles.container}>
  {array.map(box => <Text style={styles.[box.name]} key={box.name}>{box.name}</Text>)}
</View >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM