gpt4 book ai didi

javascript - React Semantic UI - 在下拉菜单中添加选项键

转载 作者:行者123 更新时间:2023-11-30 15:36:20 25 4
gpt4 key购买 nike

我有这个下拉菜单实例:

      <Dropdown
selection
options={this.state.options}
search
value={value}
onChange={this.handleChange}
onSearchChange={this.handleSearchChange}
/>

当我的后端返回响应时,它被设置为状态,它的结构如下:

"options": [
{
"text": "New York,All Airports (NYC) , USA",
"value": "NYC"
},
{
"text": "New York,Newark Liberty Intl (EWR), USA",
"value": "EWR"
},
{
"text": "New York,John F Kennedy (JFK), USA",
"value": "JFK"
},
{
"text": "New York,La Guardia (LGA), USA",
"value": "LGA"
}
]

...我收到此警告:

Warning: flattenChildren(...): Encountered two children with the same key, 1:$BLZ. Child keys must be unique; when two children share a key, only the first child will be used.

in select (created by Dropdown)
in div (created by Dropdown)
in Dropdown (created by SearchForm)

如何向这些元素添加键以防止出现此警告?

最佳答案

所以查看 Semantic UI source for the dropdown 的代码组件,渲染选项函数将您传入的选项转换为 DropdownItem 组件数组:

renderOptions = () => {
const { multiple, search, noResultsMessage } = this.props
const { selectedIndex, value } = this.state
const options = this.getMenuOptions()

if (noResultsMessage !== null && search && _.isEmpty(options)) {
return <div className='message'>{noResultsMessage}</div>
}

const isActive = multiple
? optValue => _.includes(value, optValue)
: optValue => optValue === value

return _.map(options, (opt, i) => (
<DropdownItem
key={`${opt.value}-${i}`}
active={isActive(opt.value)}
onClick={this.handleItemClick}
selected={selectedIndex === i}
{...opt}
// Needed for handling click events on disabled items
style={{ ...opt.style, pointerEvents: 'all' }}
/>
))
}

这个数组的键是通过获取值属性并将索引附加到它来设置的:

key={`${opt.value}-${i}`}

因为使用了索引,所以它应该始终是唯一的,但还有另一部分代码用于 hidden inputs

 renderHiddenInput = () => {
debug('renderHiddenInput()')
const { value } = this.state
const { multiple, name, options, selection } = this.props
debug(`name: ${name}`)
debug(`selection: ${selection}`)
debug(`value: ${value}`)
if (!selection) return null

// a dropdown without an active item will have an empty string value
return (
<select type='hidden' aria-hidden='true' name={name} value={value} multiple={multiple}>
<option value='' />
{_.map(options, option => (
<option key={option.value} value={option.value}>{option.text}</option>
))}
</select>
)
}

在这一个中,键只设置为值,而不是值加上索引。

 <option key={option.value} value={option.value}>{option.text}</option>

这可能是您的问题,如果您有重复值,则键将不是唯一的。仔细检查选项列表以确保您没有重复的值。

关于javascript - React Semantic UI - 在下拉菜单中添加选项键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41472081/

25 4 0