最近做项目时,要解决有后台数据ID元素就显示,没有ID就隐藏。困惑许久,最后boss10秒钟帮我解决了。
1.了解三元运算符:
javascript中的三目运算符,也叫三元运算符,属于运算符里面的一种。
基本语法为: expression ? sentence1 : sentence2
表示当expression的值为真时,会执行sentence1,否则执行 sentence2
2.代码实例:
import React from 'react';
import styles from './index.css';
import { connect } from 'dva';
import { Button } from 'antd';
@connect(({ news }) => ({
...news,
}))
class Details extends React.Component {
loadDetails(Id) {
const parentId = this.props.history.location.query;
if (!Id) {
Id = parentId.id;
}
this.props.dispatch({
type: 'news/getNewsdetail',
payload: {
id: Id,
},
});
}
componentWillMount() {
this.loadDetails();
}
render() {
const news = this.props.news || { PreNews: [{ Title: '' }], NextNews: [{ Title: '' }] };
return (
// 资讯详情页
<div className={styles.Details}>
<div className={styles.banner}>
<img src={require('@/assets/images/banner2.png')} alt="" />
</div>
<div className={styles.content}>
<div className={styles.Box}>
<div className={styles.Title}>{news.title}</div>
<span className={styles.Time}>{news.pubTime}</span>
<div className={styles.TxtBox}>
<div className={styles.TxtBox_Top}>
<div dangerouslySetInnerHTML={{ __html: news.context }} />
</div>
</div>
</div>
{/* 上下篇文章切换部分 */}
<span className={styles.post_nav_line} />
<div className={styles.post_nav_box}>
{/* 当值为undefined或null,不会被渲染 */}
{news.PreNews.id ? (
<div className={styles.post_nav_prev} onClick={e => {}}>
<Button
onClick={e => {
this.lookPrevious(news.PreNews.id);
}}
>
<span>上一篇:{news.PreNews.Title}</span>
</Button>
</div>
) : ( undefined)}
{news.NextNews.id ? (
<div className={styles.post_nav_next}>
<Button
onClick={e => {
this.lookLast(news.NextNews.id);
}}
>
<span>下一篇:{news.NextNews.Title}</span>
</Button>
</div>
) : (
undefined
)}
</div>
</div>
</div>
);
}
// 上一篇
lookPrevious(id) {
if (id) {
this.loadDetails(id);
}
}
// 下一篇
lookLast(id) {
if (id) {
this.loadDetails(id);
}
}}
export default Details;
这样,当没有从后台传来ID时,元素就不会被react渲染,会被隐藏
网友评论