繁体   English   中英

如果在 react.js(basic) 中

[英]If else in react.js(basic)

我第一次使用 spotifys api 键在 react.js 上构建一个简单的单页应用程序。 当用户播放歌曲时,我设法在页面上获取歌曲信息。 如何向其中添加 else 语句,以便在没有播放任何内容时出现“未检测到播放”之类的内容?

{ (() => {
          if (this.state.nowPlaying.id) {

            return (
              <div>
                <div> Now Playing: { this.state.nowPlaying.name} </div>
                <div> By: { this.state.nowPlaying.artist} </div>
                <div> Id: { this.state.nowPlaying.id} </div>
                <div> Progress: { this.state.nowPlaying.progress} </div>
                <div>
                  <img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
                </div>
                <AudioFeatures
                 id={this.state.nowPlaying.id}
                 ref={this.audioFeatures}
                 oAuth={this.state.oAuth}
                />
              </div>
            );
          } 
        }

        })()
      }

谢谢。

React 文档中的这个页面讨论了条件渲染的各种选项。

如果可能的话,我喜欢做的JSX表达我要在嵌入之前的条件部分,但如果你想它嵌入在表达式,你可以使用条件运算符(覆盖在该网页在这里),而不是创建和运行临时箭头函数:

{ this.state.nowPlaying && this.state.nowPlaying.id
  ?      <div>
          <div> Now Playing: { this.state.nowPlaying.name} </div>
          <div> By: { this.state.nowPlaying.artist} </div>
          <div> Id: { this.state.nowPlaying.id} </div>
          <div> Progress: { this.state.nowPlaying.progress} </div>
          <div>
            <img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
          </div>
          <AudioFeatures
           id={this.state.nowPlaying.id}
           ref={this.audioFeatures}
           oAuth={this.state.oAuth}
          />
        </div>
  :     <div>No Playback detected</div>
}

但同样,我会在 JSX 表达式之前这样做以简化事情:

let nowPlaying;
if (this.state.nowPlaying && this.state.nowPlaying.id) {
    newPlaying = <div>
     <div> Now Playing: { this.state.nowPlaying.name} </div>
     <div> By: { this.state.nowPlaying.artist} </div>
     <div> Id: { this.state.nowPlaying.id} </div>
     <div> Progress: { this.state.nowPlaying.progress} </div>
     <div>
       <img src={ this.state.nowPlaying.image} style={{ width: 100}}/>
     </div>
     <AudioFeatures
      id={this.state.nowPlaying.id}
      ref={this.audioFeatures}
      oAuth={this.state.oAuth}
     />
    </div>;
} else {
    nowPlaying = <div>No Playback detected</div>;
}

然后在您的 JSX 表达式中:

{nowPlaying}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM