ReactJS - 在组件

时间:2017-07-03 18:50:47

标签: javascript reactjs

我正在尝试创建两个组件,一个用于保存iTunes中API调用的结果。我希望能够点击其中任何一个项目并将其移至空组件moveResults,然后再次单击它将其移回searchResults。从其他练习中,我觉得我很接近,但是我一直收到关于this.handleEvent = this.handleEvent.bind(this)的错误。关于我可能出错的地方和一些可能的解决方案的任何想法?

 var App = React.createClass({
 getInitialState: function() {
    return {
        searchResults: [],
        moveResults: []
    }

},

this.handleEvent = this.handleEvent.bind(this);

showResults: function(response) {
    this.setState({
        searchResults: response.results,
        moveResults: []
    })
},

search: function(URL) {
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response) {
            this.showResults(response);
        }.bind(this)
    });
},

handleEvent(trackId) {
    const isInSearchResults = this.state.searchResults.includes(trackId);

    this.setState({
        searchResults: isInSearchResults ? this.state.searchResults.filter(i => i !== trackId) : [...this.state.searchResults, trackId],
        moveResults: isInSearchResults ? [...this.state.moveResults, trackId] : this.state.moveResults.filter(i => i !== trackId)
    });
},

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=broods')
},

render: function(){
    return (
        <div>
            <Results searchResults={this.state.searchResults} handleEvent={this.handleEvent}/>
            <Results searchResults={this.state.moveResults} handleEvent={this.handleEvent} />
        </div>
    );
  }
});


var Results = React.createClass({
   render: function(){
    let handleEvent = this.props.handleEvent;
    var resultItems = this.props.searchResults.map(function(result) {
        return <ResultItem key={result.trackId} trackName={result.trackName} onClick={() => handleEvent(resultItems.id)} />
    });
    return(
        <ul>
            {resultItems}
        </ul>
    );
  }
});
var ResultItem = React.createClass({
   render: function(){
    return <li> {this.props.trackName} </li>;
   }
 });

  ReactDOM.render(
       <App />, document.getElementById('root')
   );

0 个答案:

没有答案