我有一个从 API 收到的轨道数组[]。 我将其传递给 map 函数,该函数将为轨道中的每个轨道返回一个轨道。我想导出特定于该轨道的变量(歌曲),以便在我的事件处理程序中进行处理。唯一不起作用的是歌曲的范围。我无法在 map 函数中设置歌曲的状态,否则组件会进入无限重新渲染循环。
handleEnter(){
//I want to get the song into this context and play it here
this.props.mouseEnter();
}
handleLeave(){
//same for pausing
this.props.mouseLeave();
}
createTrack(track){
var song = new Audio([track.preview_url]);
return (
<div className="image" key={track.id}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={this.handleEnter.bind(this)}
onMouseLeave={this.handleLeave.bind(this)}
/>
<p className="showMe"><span>{track.name}</span></p>
</div>
);
}
getTracks(){
if(this.props.tracks) {
console.log(this.props.tracks);
return (
<div>{this.props.tracks.map(track => this.createTrack(track))}</div>
);
}
}
componentWillMount(){
this.props.fetchMessage();
}
render(){
return(
<div>{this.getTracks()}</div>
)
}
最佳答案
如果您想使用.bind,可以发送至handleEnter
和handleLeave
.
handleEnter( trackID ) {
// trackID available here
}
createTrack(track){
var song = new Audio([track.preview_url]);
return (
<div className="image" key={track.id}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={this.handleEnter.bind( this, track.id )}
onMouseLeave={this.handleLeave.bind( this, track.id )}
/>
<p className="showMe"><span>{track.name}</span></p>
</div>
);
}
通常是 best practice不要在 React 中使用 .bind,因为它会在每次渲染时创建一个新函数。相反,您应该创建一个 <Track />
组件,将其传递给轨道,然后传递 handleEnter
和handleLeave
作为 Prop 。
const track = ( props ) => {
let { track, handleEnter, handleLeave } = props;
const onMouseEnter = () {
handleEnter( track.id );
}
const onMouseLeave = () {
handleLeave( track.id );
}
return (
<div className="image" key={track.id}>
<img
className="img-circle"
src={track.album.images[0].url}
onMouseEnter={ onMouseEnter }
onMouseLeave={ onMouseLeave }
/>
<p className="showMe">
<span>{track.name}</span>
</p>
</div>
);
};
然后在你的渲染中,你会像你正在做的那样进行映射并输出 <Track />
pure components而不是完整的组件
关于javascript - 我认为这是另一个 React/JS 上下文问题,我如何提取这个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39070295/