Jaz*_*Cat 1 components parent-child reactjs
在从child设置父级中的可访问实例变量之前有一些问题.
事实证明,你不能以我想要的方式设置来自孩子的父变量.我继续并成功调用了setState,但是每次设置它时状态本身似乎都会改变,我不会覆盖Howler状态(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')
Run Code Online (Sandbox Code Playgroud)
你的代码中有很多不正确的东西.我建议去官方的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>
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2464 次 |
| 最近记录: |