react-router - 如何更改 url [英] react-router - how change the url

查看:155
本文介绍了react-router - 如何更改 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让用户编辑 url,路径"出现在其他组件的输入中,并且在搜索输入时实时更改 url.如何使用withRouter"来执行此功能?

//App.js 组件类 App 扩展组件 {使成为() {const { 匹配,位置,历史} = this.props;返回 (<div ><搜索searchString={location.pathname}/>

)}}使用Router(App)导出默认值//Search.js 组件const Search = ({ searchString }) =>(<div><输入值={搜索字符串}类型=搜索"占位符=搜索"咏叹调标签=搜索"/>

)

解决方案

这应该对你有用,虽然我不确定在输入搜索输入时将用户重定向到另一个页面是一个很好的用户体验.

//App.js 组件类 App 扩展组件 {状态 = {searchString: this.props.location.pathname}handleSearch = (事件) =>{这个.setState({ searchString: event.target.value },() =>this.props.history.push('/search?query=' + this.state.searchString));}使成为() {返回 (<div ><搜索onChange={this.handleSearch}searchString={this.state.searchString}/>

)}}使用Router(App)导出默认值const Search = ({ searchString, onChange }) =>(<div><输入onChange={onChange}值={搜索字符串}类型=搜索"占位符=搜索"咏叹调标签=搜索"/>

)

I need to have the user edit the url the "path" appears in the input of the other component and when searching the input change the url in real time. How can I use "withRouter" to perform this function?

// App.js component

    class App extends Component {

      render() {
        const { match, location, history } = this.props;

        return (
          <div >
              <Search
                searchString={location.pathname}
              />
          </div>
        )
      }
    }

    export default withRouter(App)

//Search.js component  

    const Search = ({ searchString }) => (
            <div>
                <input
                    value={searchString} 
                    type="search"
                    placeholder="Search"
                    aria-label="Search"
                />
            </div>
    )

解决方案

This should work for you although I'm not sure redirecting user to another page while typing into search input is a good UX.

// App.js component

    class App extends Component {
      state = {
        searchString: this.props.location.pathname
      }

      handleSearch = (event) => {
        this.setState(
          { searchString: event.target.value },
          () => this.props.history.push('/search?query=' + this.state.searchString)
        );
      }

      render() {
        return (
          <div >
              <Search
                onChange={this.handleSearch}
                searchString={this.state.searchString}
              />
          </div>
        )
      }
    }

    export default withRouter(App)


    const Search = ({ searchString, onChange }) => (
            <div>
                <input
                    onChange={onChange}
                    value={searchString} 
                    type="search"
                    placeholder="Search"
                    aria-label="Search"
                />
            </div>
    )

这篇关于react-router - 如何更改 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆