react-router - 如何改变 url

react-router - how change the url

我需要让用户编辑 url,"path" 出现在另一个组件的输入中,并在搜索输入时实时更改 url。如何使用 "withRouter" 来执行此功能?

// 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>
    )

虽然我不确定在输入搜索输入时将用户重定向到另一个页面是否是一个很好的用户体验,但这应该适合您。

// 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>
    )