gpt4 book ai didi

javascript - if else 在react.js中(基本)

转载 作者:行者123 更新时间:2023-12-01 00:03:03 25 4
gpt4 key购买 nike

我第一次使用spotifys api key 在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>
);
}
}

})()
}

谢谢。

最佳答案

This page React 文档中讨论了条件渲染的各种选项。

在可能的情况下,我更喜欢在要嵌入的 JSX 表达式之前执行条件部分,但如果您希望将其嵌入到该表达式中,则可以使用条件运算符(在该页面 here 中介绍)而不是创建并运行临时箭头函数:

{ 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}

关于javascript - if else 在react.js中(基本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com