reactjs如何使用refs

时间:2018-05-12 14:15:55

标签: reactjs refs

我是Reactjs的新手。我正在尝试制作一个故事播放器(如音频播放器,但有故事)。

https://i.stack.imgur.com/WX6sI.jpg

render() {
    const storiesList = this.props.stories;
    return(
        <div>
            {
                storiesList.map((story, k) => {
                return(
                    <div
                        ref={this.myRef}
                        key={k}
                        className="story"
                        onClick={() => this.playAudio(story.playing_url)}
                        onChange={console.log(this.myRef.current)}
                    >
                        <img 
                            src={story.image_url}
                            className="story-img"
                            alt="story"
                        />
                        <div className="story-play">
                            <div className="story-play-inner">
                            {
                                this.state.playing_story === story.playing_url && this.state.playing
                                ? <span>&#124; &#124;</span>
                                : <span>&#9654;</span>
                            }
                            </div>
                        </div>
                        <p className="story-name">
                            {story.name}
                        </p>

                    </div>
                )
            })}
            <div className="progress-bar" >

            <div className="playBtn">
                <span>&#9654;</span>
            </div>
            <div className="progress-container">
                <div className="progress-title">
                    <span>Story name</span>
                </div>
                <div className="timeline">
                    <div className="playhead"></div>
                </div>
            <div className="progress-time">
                <span className="progress-time-played">4:55 </span>
                <span className="progress-time-total">/ 8:15</span>
            </div>
            </div>

        </div>

         </div>
    )
}
}

当我控制日志时,它总是返回相同的4个故事。如何访问我点击的元素的参考?我需要这样做,以便我可以在进度条上渲染故事名称。

1 个答案:

答案 0 :(得分:1)

此处不需要ref - 相反,只需将整个story传回您的onClick回调:

// instead of this
onClick={() => this.playAudio(story.playing_url)}
// do this
onClick={() => this.playStory(story)}

然后,您可以在setStateplayStory,以便this.state.story成为当前正在播放的故事。

playStory(story) {
  this.setState({ story: story });
  this.playAudio(story.playing_url);
}

render方法中,您只需查看this.state.story

var story_title = null;
if (this.state && this.state.story) {
  story_title = <span className="story-title">{this.state.story}</span>;
}

return (
  <!-- ... snip ... -->
  <div className="progress-title">
    {story_title}
  </div>
);