在從父項中設置可訪問的實例變量之前有一些問題。React handleClick在父項中
事實證明,你不能以我想要的方式設置孩子的父母孩子。我繼續併成功地調用setState,但狀態本身似乎每次改變我設置它,我不覆蓋咆哮狀態(this.state.howler),我只是實例化另一個...
沒有解決我的原始問題與音樂同時播放。
的狀態不應該改變,以前的狀態應該(?)被覆蓋時
this.setState({ howler: howlerInstance, });
叫?一點都不明白。
// Components
var SongContainer = React.createClass({
getInitialState: function() {
return {
data: [],
howler: 0,
};
},
handleUserInput : function(howlerInstance) {
this.state.howler.stop();
this.setState({
howler: howlerInstance,
});
this.state.howler.play();
},
loadTrackListFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data.playlist});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadTrackListFromServer();
setInterval(this.loadTrackListFromServer, this.props.pollInterval);
this.state.howler.stop().play();
},
render: function() {
return (
<div className="container songsContainer">
<SongList howler={this.state.howler} onUserInput={this.handleUserInput} data={this.state.data} />
</div>
);
}
});
var SongList = React.createClass({
handleChange: function(howlerInstance) {
this.props.onUserInput(
howlerInstance
);
},
render: function() {
var i = 0;
var self = this;
var trackNodes = this.props.data.map(function(track, i) {
return (
<Song onUserClick={self.handleChange} key={i} >
{track}
</Song>
);
i++;
});
return (
<div className="row">
<div className="col-sm-12">
<div className="list-group-wrapper">
<div className="list-group">
{trackNodes}
</div>
</div>
</div>
</div>
);
}
});
var Song = React.createClass({
handleClick : function(e) {
console.log(2);
e.preventDefault();
var song = new Howl({
urls: [e.target.href]
});
this.props.onUserClick(
song
);
},
render: function() {
return (
<a href={'/static/mp3s/' + this.props.children.toString()} onClick={this.handleClick} className="list-group-item song">
{this.props.children}
</a>
);
}
});
ReactDOM.render(
<SongContainer url="/playlist" pollInterval={2000} />,
document.getElementById('content')
什麼是'this.props.children.toString()'?你從哪裏得到這個想法? – azium
此外,使用以下語法:'onClick = {this.handleClick(this,event,this.props.children.toString())}'您不將該函數附加到'onClick',而是分配'return'值。此外......'Song'甚至沒有'handleClick'功能!您必須使用'SongContainer'中的道具來傳遞這個道具 – azium
您在'SongList'中定義的'onClick'函數並未在任何地方使用! – azium