【问题标题】:how to link to a page with picked item from dropdown如何从下拉列表中链接到带有所选项目的页面
【发布时间】:2021-06-24 08:07:26
【问题描述】:

我正在为我的 Web 应用程序使用 react-select 我有一个带有自动填充功能的下拉菜单,当我单击输入时,我将看到来自 API 的所有汽车项目的列表,但我需要输入所需的项目并重定向到该详细信息页面。 我应该为此创建路线吗?

看看:

当我点击 BMW 时,我需要进入 bmw 详细信息页面。 如果它只是简单的汽车项目,我会在链接下创建一个按钮

<Link  className='btn-item auction-btn mr-2' to={`/carDetails/${item.id}`}>Details</Link>.

带路由:

 <Route
            exact
            path="/carDetails/:id"
            render={({ match }) => (
              <CarDetails item={data.find((item) => String(item.id) === String(match.params.id))} />
            )}
          />

但这是 react-select 库,它是我必须过滤的组件,而不是转到我需要的页面..

【问题讨论】:

    标签: javascript reactjs react-native react-hooks react-select


    【解决方案1】:

    您可以在 react-select 的更改处理程序中执行 history.push。一个例子:

    export default function MyComponent() {
      const [value, setValue] = useState()
      const history = useHistory()
    
      function handleChange(newValue) {
        setValue(newValue)
        history.push(`/carDetails/${newValue.id}`)
      }
    
      return (
        <Select
          value={value}
          options={options}
          onChange={handleChange}
        />
      )
    }
    

    【讨论】:

    • 此外,如果您要离开当前组件并使用 history.push 重定向到其他组件,则可能不需要在更改处理程序中使用 setValue(newValue)
    • idk 为什么但 (/carDetails/${newValue.id}) 未定义
    • {标签:“法拉利加利福尼亚”,价值:“法拉利加利福尼亚”} 标签:“法拉利加利福尼亚”价值:“法拉利加利福尼亚”
    • 未定义是重定向到carDetails/${newValue.id}
    • 这意味着您在传递给react-selectoptions 中没有id。您可以将id 添加到您的options 吗?之后它应该可以工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2013-06-18
    • 2015-09-28
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多