【问题标题】:Send user to a link from search bar query将用户发送到搜索栏查询中的链接
【发布时间】:2021-09-18 20:06:32
【问题描述】:

我有一个搜索栏,用户点击回车后,它会将他们带到一个链接,其中包含搜索栏中的任何内容。

在我的 app.js 我有这条路线

<Route path='/web/:something' component={() => 
   <SearchResults />
}/>

然后我有一个搜索组件

|const Search = () => {

    const [query, setquery] = useState(null)

    const onClick2= () => {
        var x = document.getElementById("navBarSearchForm").value;
        if(x) {
          setquery(x)
        }
    }
    console.log(query)
    
    return (
        <div className="search">
            <div className="input-group">
                <input type="search" id="navBarSearchForm" className="form-control rounded" placeholder="Enter Website URL To Get Analytics" aria-label="Search"
                 aria-describedby="search-addon"></input>
                 <button onClick={onClick2} type="button" id="searchbutton" className="btn btn-outline-primary"><Link to={`/web/${query}`}>search</Link></button>
            </div>
        </div>
    )
}

export default Search

这样做的问题是,无论用户在搜索栏中输入什么内容,都会将其设为 null,例如 localhost:3000/web/null,这可能是因为它将用户发送到状态有时间改变之前的链接?

为了尝试解决这个问题,我将搜索按钮包裹在一个三元运算符中,如下所示:

        <div className="search">
            <div className="input-group">
                <input type="search" id="navBarSearchForm" className="form-control rounded" placeholder="Enter Website URL To Get Analytics" aria-label="Search"
                 aria-describedby="search-addon"></input>
                 {website ?
                  (<button onClick={onClick2} type="button" id="searchbutton" className="btn btn-outline-primary"><Link to={`/web/${query}`}>search</Link></button>)
                :
                  (<button onClick={onClick2} type="button" id="searchbutton" className="btn btn-outline-primary"><Link to={`/`}>search</Link></button>)}
            </div>
        </div>

现在,这可行,但唯一的问题是用户必须双击搜索按钮,这并不理想。我该如何解决这个问题,以便他们只需单击一下就可以链接到他们在搜索栏中输入的任何内容?

或者有更好的方法吗?

【问题讨论】:

    标签: reactjs react-hooks react-router


    【解决方案1】:

    你可以使用useHistoryreact-router-dom钩子,然后使用历史对象的push方法去新的路由。

    import {useHistory} from 'react-router-dom';
    
    const Component = () => {
        const history = useHistory();
        
        ...
        
        const onClick = () => {
            history.push(yourRouteOfChoice);
        };
        
        ...
        
        return (
            <div onClick={onClick}>
                ...
            </div>
        );
    };
    

    顺便说一句,为你的函数使用一些更好的命名,它将在未来帮助你。

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      相关资源
      最近更新 更多