简体   繁体   English

使用React.JS选择-动态填充的选项

[英]Select with React.JS - dynamically populated options

I am trying to populate select in [stateless component of] React/Redux app as: 我正在尝试将React / Redux应用程序的[无状态组件]中的select填充为:

const FillSelect = ({team}) => <option value={team.onboardingOrder}>{team.name}</option>

const TeamSelector = ({teams}) => {
  return (
    <select>
      <option value="">All</option>
      {
        teams ? (teams => teams.map(team => <FillSelect team={team} />)) : null
      }
    </select>
  )
}

Teams looks like: {0:{id: 1, name: "Program Management", onboardingOrder: 0, …}, 1: {id: 2, name: "Value Capture", onboardingOrder: 1, …}…} . 团队看起来像: {0:{id: 1, name: "Program Management", onboardingOrder: 0, …}, 1: {id: 2, name: "Value Capture", onboardingOrder: 1, …}…}

It returns an error: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in select ... 它返回一个错误: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in select ... Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in select ...

Is this happening because I am using map() ? 这是因为我正在使用map()吗? What is the correct way of doing this? 正确的做法是什么?

You're not calling map directly; 您不是直接致电地图;而是 if teams is truthy, you return a function ( teams => ... ). 如果teams是truthy,返回一个函数( teams => ... )。 You probably wanted the line to look like this: 您可能希望该行如下所示:

teams ? teams.map(team => <FillSelect team={team} />) : null

Which would yield an array of <FillSelect /> 's. 这将产生一个<FillSelect />的数组。

This works fine: 这工作正常:

  return (
    <select>
      <option value="">All</option>
      {
        Object.values(teams).map((team, i) => <option value={team.onboardingOrder} key={i}>{team.name}</option> )
      }
    </select>
  )

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

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