访问另一个在 React Native 中设置为变量的对象

Access an object inside an other who is set as variable in React Native

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

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

我用传递的 prop 调用我的组件的地方:

<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 访问时没有错误。

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

如果您像下面这样更改您的组件

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

以及如下样式

backgroundColor: service[site].color,

它会起作用的。 你也应该改变你提到这个的其他地方。