2016-08-03 55 views
0

所以,我基本上有這Home組件,它具有SearchForm組件和PostBox組件顯示今天的API數據。更改道具值

var Home = React.createClass({ 
    handleSubmitSearch: function (e) { 
    e.preventDefault(); 
    // change the URL 
    }, 
    render: function() { 
    return (
     <div className="home"> 
     <SearchForm 
      onSubmitSearch={this.handleSubmitSearch} /> 
     <PostBox 
      url="http://localhost:3000/posts/today" 
      pollInterval={2000} /> 
     </div> 
    ) 
    } 
}); 

的事情是,在SearchForm提交按鈕被觸發時,我想基本上是通過發送請求到另一個API像http://localhost:3000/posts/search/query而不是顯示今天的數據結果顯示爲PostBox。 我的問題是,我怎樣才能改變PostBox的url道具改爲handleSubmitSearch()

+0

您不改變'道具'。組件'道具'應該被視爲不可變的。如果某個組件需要存儲可以更改的數據,請改用'state'。 – naomik

回答

2

在這種情況下,我會將url置於狀態並在提交表單時更改它。

var Home = React.createClass({ 
    getInitialState: function() { 
    return {url: 'http://localhost:3000/posts/today'}; 
    }, 
    handleSubmitSearch: function (e) { 
    e.preventDefault(); 
    var value = ''; // TODO: get value that you want 
    this.setState({ 
     url: 'http://localhost:3000/posts/' + value, 
    }); 
    }, 
    render: function() { 
    return (
     <div className="home"> 
     <SearchForm 
      onSubmitSearch={this.handleSubmitSearch} /> 
     <PostBox 
      url={this.state.url} 
      pollInterval={2000} /> 
     </div> 
    ) 
    } 
});