【问题标题】:How to add attribute selected to select React?如何添加选择的属性以选择 React?
【发布时间】:2021-04-19 06:38:04
【问题描述】:

我有这个代码

{categories.map((category, index) => {
  return(
    <option value={category._id} key={index}>{category.name}</option>
  )
})}

此代码显示所有类别。我有const product

如果product.category == category._id添加属性selected到select(在map函数中)怎么做

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    试试这个,这应该可以解决您的问题。我已根据您在 map 函数中的要求应用了条件。

    {categories.map((category, index) => {
      return(
        product.category == category._id ? <option value={category._id} key={index} selected>{category.name}</option>: <option value={category._id} key={index}>{category.name}</option> 
      )
    })}
    

    【讨论】:

      【解决方案2】:

      您可以使用selected={product.category == category._id},但不推荐,您应该在select 标签中使用value 属性。 Reference

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 2023-03-04
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多