在从子级设置父级中的可访问实例变量之前有一些问题。
事实证明,你不能以我想要的方式设置来自孩子的父变量。我继续并成功调用了setState,但是每次设置它时状态本身似乎都会改变,我不会覆盖Howler状态(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')
答案 0 :(得分:5)
您的代码中存在许多不正确的内容。我建议去官方的React文档并从那里的教程开始。
对于我的回答,我将尝试解决从父到子传递函数的概念。
var SongList = React.createClass({
logTrack: function(track) {
console.log(track)
}
render: function () {
var trackNodes = this.props.data.map(function(track, i) {
return (
<Song
key={i}
handleClick={this.logTrack} // pass function through props
>
{track}
</Song>
);
});
return (
<div className="row">
{trackNodes}
</div>
);
}
})
var Song = React.createClass({
render: function () {
<a onClick={ function () { this.props.handleClick('some value') }>
{this.props.children}
</a>
}
})