简体   繁体   English

有没有办法在地图函数之外传递参数 - ReactJS - Typescript

[英]Is there a way to pass parameter outside of map function - ReactJS - Typescript

At the moment i get from the Back End an array of objects that looks like this :目前我从后端得到了一个看起来像这样的对象数组:

const myArr = [ 
   { 
    A: "Ananas", 
    B: "Banana", 
    C: "Citroen"
   }
]

I want to display a single JSX select menu per row with the options from the Array Ananas , Banana , Citroen .我想每行显示一个 JSX 选择菜单,其中包含来自 Array Ananas , Banana , Citroen的选项。 That's why I am using this method:这就是我使用这种方法的原因:

<Select onChange={(e: any) => handleChange(e)}>
   {myArr [0] &&
    Object.entries(myArr [0]).map(([key, value]) => (
     <MenuItem value={value}>{value}</MenuItem>
   ))}
</Select>

But the thing is that in order to keep the good JSX structure I have to keep the Select outside of my .map() function otherwise I will have many menus if it is inside.但问题是,为了保持良好的 JSX 结构,我必须将Select保留在我的.map()函数之外,否则如果它在里面,我会有很多菜单。

My ultimate goal is to pass the key parameter from the .map() function back to the Select .我的最终目标是将.map()函数中的key参数传递回Select

<Select name={key} onChange={(e: any) => handleChange(e)}>

EDIT : So behind the scenes it will look like :编辑:所以在幕后它看起来像:

<Select name="A"> 
  <MenuItem value="Ananas">Ananas</MenuItem>
  <MenuItem value="Banana">Banana</MenuItem>
  <MenuItem value="Citroen">Citroen</MenuItem>
</Select>

<Select name="B"> 
  <MenuItem value="Ananas">Ananas</MenuItem>
  <MenuItem value="Banana">Banana</MenuItem>
  <MenuItem value="Citroen">Citroen</MenuItem>
</Select>

<Select name="C"> 
  <MenuItem value="Ananas">Ananas</MenuItem>
  <MenuItem value="Banana">Banana</MenuItem>
  <MenuItem value="Citroen">Citroen</MenuItem>
</Select>

EDIT 2.0 : If we wrap everything into one loop so that we can have access to everything like this :编辑 2.0 :如果我们将所有内容都包装成一个循环,以便我们可以访问这样的所有内容:

   { myArr [0] &&
      Object.entries(myArr [0]).map(([key, value]) => (
       <Select name ={key} onChange={(e: any) => handleChange(e)}>
         <MenuItem value={value}>{value}</MenuItem>
       </Select>
   ))}

The render result is looking like this :渲染结果如下所示: 在此处输入图片说明

And this is something that we defenately do not want to see这是我们绝对不想看到的

I do not know if this is possible, but still I prefer to ask.我不知道这是否可能,但我还是想问问。 I hope there is someone that can give me an inside of the issue or at least a way to fix my issue.我希望有人可以给我一个问题的内部或至少一种解决我的问题的方法。 Huge thanks!非常感谢!

Looks like you'll need a nested map() .看起来你需要一个嵌套的map() One on the Object.keys() to create the select elements and one on the Object.values() to populate each select. Object.keys()上的一个用于创建选择元素, Object.values()上的一个用于填充每个选择。

The snippet below achieves this using Object.entries() and passing the entries array on to the inner map() .下面的代码片段使用Object.entries()并将entries数组传递给内部map()来实现这一点。

const myArr = [ 
   { 
    A: "Ananas", 
    B: "Banana", 
    C: "Citroen"
   }
]

{
  myArr[0] && Object.entries(myArr[0]).map(([key], _, entries) => (
    <Select key={key} name={key}>
      {entries.map(([, value]) => (
        <MenuItem value={value}>{value}</MenuItem>)
      )
      }
    </Select>)
  )
}

 const App = () => { const myArr = [{ A: "Ananas", B: "Banana", C: "Citroen" }]; const handleChange = e => { console.log(`${e.target.name}: ${e.target.value}`); }; return ( <div> {myArr[0] && Object.entries(myArr[0]).map(([key], _, entries) => ( <select key={key} name={key} onChange={handleChange}> {entries.map(([, value]) => ( <option value={value}>{value}</option>) ) } </select>) )} </div> ); } ReactDOM.render( <App />, document.getElementById("root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

As a suggestion from @Yoshi this is the correct following answer to my problem.作为@Yoshi 的建议,这是对我的问题的正确以下答案。 Because i am importing my static row names from another file like this :因为我正在从另一个文件导入我的静态行名称,如下所示:

textDisplay.js文本显示.js

 export default [
       {
         label: 'Fruits',
         required: true,
       },

       {
        label: 'Fruits 2',
        required: true,
       },

       {
       label: 'Fruits 3',
       required: true,
       },
    ]

So that i can have a structure to display like the following picture :这样我就可以有一个结构来显示如下图: 在此处输入图片说明

@Yoshi Here's the idea: When we map over textDisplay with: textDisplay.map((column, i) => (...) we have an index i, this will be 0, 1, 2. What we need to do is, get the correct key from myArr by using that index. @Yoshi 这里的想法是:当我们使用 textDisplay.map((column, i) => (...) 映射 textDisplay 时,我们有一个索引 i,这将是 0、1、2。我们需要做的是,使用该索引从 myArr 获取正确的密钥。

 // importing our text data to display 
    import textDisplay '../../textDisplay.js'
    const foo = () => {
      // incoming data
      const myArr = [
        {
          A: "Ananas",
          B: "Banana",
          C: "Citroen"
        }
      ];
    
      const items = myArr[0];
      const keys = Object.keys(items);
      const values = Object.values(items);
    
      return (
        <List>
          {textDisplay.map((column, i) => (
            <ListItem key={column.keyValue}>
              <ListItemText>
                {column.label} {column.required ? '*' : ''}
              </ListItemText>
              <FormControl className={classes.formControl}>
                <Select name={keys[i]} onChange={(e: any, id) => handleChange(e, id)}>
                  {values.map(value => (
                    <MenuItem value={value}>{value}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </ListItem>
          ))}
        </List>
      );
    };

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

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