【问题标题】:React Native: pass different styles in a mapReact Native:在地图中传递不同的样式
【发布时间】:2020-08-06 13:24:51
【问题描述】:

我想要 4 个盒子,每个盒子都有不同的颜色,我想从 map() 加载每个样式。下面的代码无法编译,我写了它是为了让你明白我想要做什么。错误来自样式内部的视图。{box.name},我想代替 {box.name} 放置数组的元素,以便该函数可以采用样式表的道具。

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',
    },
});

【问题讨论】:

  • 尝试将{styles.{box.name}}更改为{styles[box.name]}
  • 是的,它成功了,谢谢

标签: javascript react-native flexbox


【解决方案1】:

{styles.{box.name}} 更改为{styles[box.name]}。查看此Q & A 了解更多详情。

【讨论】:

    【解决方案2】:

    尝试如下:

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

    【讨论】:

    • 您能否编辑您的答案以包含它的工作原理?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2018-05-13
    • 2016-10-01
    • 2016-08-05
    相关资源
    最近更新 更多