【问题标题】:Access an object inside an other who is set as variable in React Native访问在 React Native 中设置为变量的其他对象中的对象
【发布时间】:2020-11-04 17:26:17
【问题描述】:

我想访问我从资产文件调用的对象内的对象属性:

const services = {
    
    facebook: {
        name: "facebook",
        color: "#28A2F3"
    },
    spotify: {
        name: "spotify",
        color: "#42D778"
    }
    
  }

  module.exports = services

我的组件:

export default function PasswordCard({icon, color}, props) {
    return (
        <View style={{
            padding: 20,
            backgroundColor: service[props.site].color,
            elevation: 2,
            borderRadius: 5,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-evenly",
            marginTop:5,
            marginBottom: 5,
        }}>
            <Icon style={styles.service} name={service[props.site].name} size={27} color="white" />
            <View style={styles.TextContainer}>
                <Text style={styles.Text}>k.adesida@provi.data</Text>
                <Text style={styles.Text}>+213 (0) 384639293</Text>
            </View>
            <TouchableHighlight style={styles.icon}>
                <BenjaminButton name="eye" size={22} color="white" />
            </TouchableHighlight>
        </View>
    )
}

我用传递的道具调用我的组件:

<View style={styles.CardContainer}>
   <PasswordCard site={"facebook"} />
   <PasswordCard site={"spotify"} />
</View>

我得到的错误:

TypeError: undefined is not an object (evaluating 'service[props.site].color')

但是当我尝试使用 service.facebook.name 访问时没有错误。

【问题讨论】:

    标签: arrays json react-native assets react-props


    【解决方案1】:

    props 始终是第一个参数,因此当您将 props 作为第二个参数访问时,它将是未定义的,当您使用它时会出现上述错误

    如果你像下面这样改变你的组件

    function PasswordCard({icon, color,site}) {
    

    还有如下样式

    backgroundColor: service[site].color,
    

    它会起作用的。 此外,您应该更改引用此内容的其他地方。

    【讨论】:

    • 完美运行,感谢您的帮助和解释
    猜你喜欢
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多