首页 > 解决方案 > 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 个故事。如何访问我单击的元素的引用?我需要这样做,以便我可以在进度条上呈现故事名称。

标签: reactjsrefs

解决方案


这里不需要refs - 相反,只需将整个传递回story您的onClick回调:

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

然后,你可以setState在里面playStory这样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>
);

推荐阅读