基于datalist选项重定向到另一个页面(Reactjs)

问题描述 投票:0回答:1

我想在选择其中一个页面时链接到其他页面。 `

                {

                    this.state.datas.map((data,i)=>(

                        <option key={i} value={data.display_name}><Link to={"/search?q="+encodeURI  (data.name)} onClick={(e)=>this.clearData(data.name)}></Link></option>

                    ))
                }

                </datalist>`  
reactjs hyperlink datalist
1个回答
0
投票

我已经尝试了几个选项,包括Link中的嵌套选项,反之亦然,但纯粹的html下拉列表似乎不适用于React Router。

不过,这是一个简单的修复:

this.state.datas.map((data,i) =>
<option 
  key={i} 
  value={data.display_name}
  onClick={(e) => {this.clearData(data.name); this.props.history.push("/search?q=" + encodeURI(data.name)) }}
>
{data.name} // Perhaps you were missing the stuff between the <option> tags too?
</option>)

如果您已正确地将组件连接到路由器,则您将在组件的props中具有历史记录对象,并且能够调用history.push,这将把用户重定向到新指定的路由。


这会在每个下拉选项上创建一个事件侦听器,因此如果您有大量数据,那么更高效的方法是在类中创建另一个事件处理程序并将其附加到select元素的onChange侦听器。

onChange = (event, data) => {
    this.clearData(data.name); 
    this.props.history.push("/search?q=" + encodeURI(data.name));
}

还有一件事,避免使用索引i作为键,因为它可能导致渲染的意外问题。尝试找到对于要渲染的元素全局唯一的值。例如,如果您恰好在数据库中指定了一个,那么data.data_id将是一个很好的密钥。

More on dangers of index as key

© www.soinside.com 2019 - 2024. All rights reserved.