【发布时间】:2016-04-15 01:08:41
【问题描述】:
在从子级设置可访问的实例变量之前遇到了一些问题。
事实证明,您不能以我想要的方式从子项中设置父变量。我继续并成功调用了 setState,但每次设置它时状态本身似乎都会改变,我没有覆盖咆哮状态(this.state.howler),我只是实例化另一个......
没有解决我原来的同时播放音乐的问题。
状态不应该改变,之前的状态应该(?)被覆盖
this.setState({
howler: howlerInstance,
});
在 SongContainer 中被调用?完全不明白。
// 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()?你是从哪里想到这样做的? -
另外,使用以下语法:
onClick={this.handleClick(this, event, this.props.children.toString())}您没有将函数附加到onClick,而是分配了return值。此外...Song甚至没有handleClick功能!您必须使用来自SongContainer的道具传递它 -
您在
SongList中定义的onClick函数没有在任何地方使用! -
Song没有神奇的props.onClick。你必须使用道具传递它..<Song onClick={ this.onClick }></Song>。而且您不要在子组件中绑定this,而是在处理函数的组件中进行绑定(并且仅当您需要传递其他参数时) -
在我看来,你在猜测你应该做什么。您是否一直在关注官方文档或一些教程?
标签: reactjs components parent-child