React Native 三目運算
阿新 • • 發佈:2021-06-15
專案中我們經常會用到三目運算,現在簡述下遇到的心得。
1、元件內直接取實體屬性需要用三目?:(this.props.userBaseVo ? this.props.userBaseVo.userUrl : '')容錯
UserBaseVo
export interface UserBaseVo { userId: number; userName: string; userUrl: string; }
ComponentUserView
export interface IProps extends IBasePageProp { userBaseVo: UserBaseVo, } export default class ComponentUserView extends React.Component<IProps> { render() { return ( <View> <Image style={style.item_left_img} source={{ uri: this.props.userBaseVo ? this.props.userBaseVo.userUrl : ''}} /> <Text style={style.item_name} numberOfLines={1}>{this.props.userBaseVo ? this.props.userBaseVo.userName : ''}</Text> </View> ); } }
2、三目運算再次參與條件判斷時要注意優先順序()
A:用區域性變數臨時儲存結果
let showStatus = this.props.evaVoList ? this.props.evaVoList.showStatus : nullif (showStatus == 3) {
B:使用優先順序()
if ((this.props.evaVoList ? this.props.evaVoList.showStatus : null) == 3) {