简体   繁体   English

反应通过 object 键作为道具

[英]react pass object key as prop

I want to pass array of strings from parent function component to child function component.我想将字符串数组从父 function 组件传递给子 function 组件。 At the child component the array should reflect the object key.在子组件中,数组应反映 object 键。

For example, send the following array from a parent BY PROP: let colors = ['red','green','white']例如,从父 BY PROP 发送以下数组:let colors = ['red','green','white']

and at the child component I have the following variable:在子组件中,我有以下变量:

let arr = [config.red, config.green, config.white, config.blue]; 

I want to take the ".red, .green, .white" from the props and then go over the config variable below:我想从道具中获取“.red,.green,.white” ,然后在下面的配置变量上获取 go:

const config: {
red: {
    base: string;
    icon: any;
    name: string;
    target: string;
};
white: {
    base: number;
    icon: any;
    name: string;
    target: string;

... ...

Be very glad for any help.很高兴得到任何帮助。 Best.最好。

Pass the array of keys to your component...将键数组传递给您的组件...

<Child colors={colors} />

then reduce that array to the matching keys from config然后将该数组缩减为config中的匹配键

const arr = props.colors.reduce(
  (acc, key) => (key in config ? [...acc, config[key]] : acc),
  []
);

I'm using reduce() instead of a simple map() in order to filter out keys that might not be in config .我使用reduce()而不是简单的map()来过滤掉可能不在config中的键。

<Child colors={["red", "green", "white"]} />

and inside Child , you can get the respective config object, using map and iterating over itChild中,您可以获得相应的config object,使用map并对其进行迭代

const arr = props.colors.map((item,index)=>{
      
       return config[item];
})

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

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