首页 > 解决方案 > 构建一个选择选项下拉列表:对象作为 React 子项无效

问题描述

我有以下 React JSX 代码片段,它从值列表中呈现选择选项下拉列表。

renderRoleDropdown(user_role) {
let values = ['a', 'b', 'c', 'd'];

return (
  <select onChange={() => /* some logic here */ }>
    {
      values.map((value, _i) => {
        let label = getDisplayLabelForValue(value);
        return <option key={value} value={value}>{label}</option>;
      })
    }
  </select>
 );
}

据我所知,这符合其他示例的工作方式——只需循环一个列表并构建一个<option>元素数组。但是,当我运行它时,我得到

对象作为 React 子对象无效(找到:带有键 {options} 的对象)。如果您打算渲染一组子项,请改用数组。

我没有使用对象,而且我显然返回了一个数组,所以想知道为什么它不喜欢这样?

谢谢!

标签: reactjsdrop-down-menujsx

解决方案


You had a lot syntax error (pascal names, no chars) - now it's works. You can also use value instead label.

I can't reflect the rest of the code - I don't know its purpose.


import React, { useState, useEffect, Component } from 'react'

let RenderRoleDropdown = () => {

    let values = ['a', 'b', 'c', 'd'];

    return (
        <select>
            {
                values.map((value, _i) => {
                    let label = "random value"
                    return <option key={value} value={value}>{label}</option>;
                })
            }
        </select>
    );
}

export default RenderRoleDropdown;

enter image description here

enter image description here


推荐阅读