2017-03-16 58 views
1

我想獲取輸入的值被捕獲,然後用該值更新部分的URL,所有通過點擊使用React,ES6等,基本上一個簡單的搜索功能更新網址與點擊與輸入的價值與反應

所以我的組件看起來是這樣的:

class SearchInput extends Component { 
    constructor() { 
    super() 

    this.state = { 
     query: '' 
    } 
    } 

    componentDidMount =() => { 
    const handleSearchURL = window.location('/search/'+this.state.query+'/some-action') 
    this.setState({ 
     handleSearch: handleSearchURL 
    }) 
    } 

    queryChange = (evt) => { 
    this.setState({query: evt.target.value}) 
    } 

    render() { 
    const { handleSearch, placeholder } = this.props 
    return (
     <form> 
     <input id="site-search" type="search" placeholder={placeholder} value={this.state.query} /> 
     <input type="submit" value="Search" onClick={this.handleSearch} /> 
     </form> 
    ) 
    } 
} 

但這只是給了我一個很大的錯誤,它似乎不喜歡window.location的。達到此目的的最佳方式是什麼?我正在使用react-router,所以如果有更好的方法,我也很高興

回答

1

您可以使用browserHistory.pushthis.context.router.push。另外componentDidMount是一個lifeCycle函數,不需要綁定,只執行一次。您還需要一個handleSearch功能和onChange事件上輸入查詢變化

class SearchInput extends Component { 
 
    constructor() { 
 
    super() 
 

 
    this.state = { 
 
     query: '' 
 
    } 
 
    } 
 
    static contextTypes = { 
 
     router: React.PropTypes.object 
 
    } 
 
    
 
    handleSearch =() => { 
 
     this.context.router.push(`'/search/${this.state.query}/some-action'`); 
 
    } 
 
    queryChange = (evt) => { 
 
    this.setState({query: evt.target.value}) 
 
    } 
 

 
    render() { 
 
    const { handleSearch, placeholder } = this.props 
 
    return (
 
     <form> 
 
     <input id="site-search" type="search" placeholder={placeholder} value={this.state.query} onChange={this.queryChange} /> 
 
     <input type="submit" value="Search" onClick={this.handleSearch} /> 
 
     </form> 
 
    ) 
 
    } 
 
}

+0

犯規'似乎工作,當我提交 – ynter

+0

靜態contextTypes = { router:React時,我在控制檯中得到「無法讀取屬性推送未定義」 .PropTypes.object }更新了答案檢查 –

+0

是的工作謝謝 – ynter

0

您可以使用"browserHistory"'react-router',然後按新的URL到這裏是這樣的:

browserHistory.push('/search/{this.state.query}/some-action')