參考資料:https://juejin.cn/post/7114063575122984973
在Vue項目的開發過程,經常會使用到JSX語法,對常用的JSX語法分類做個筆記,方便需要之時查閱
動態綁定class
數組形式:
class={[
' pt-30 pb-20 mb-20',
this.undesirable_redeem_amt > 0 ? 'line-bottom' : '',
]}
JS模板字符串形式:
className={
`pt-30 pb-20 mb-20
${this.undesirable_redeem_amt > 0 ? 'line-bottom' : ''}
}
文本插值 單大括號{}
在單大括號內支持任何有效的JavaScript表達式
const element = <h1>Hello, { name }</h1>
條件渲染
this.isSingleProductRedeemType && tips.push(<p>若部分取出,單產品贖回份額不少於1萬份</p>)
if(flag) {
return <h1>預約</h1>}
else {
return <h1>已預約<h1>
}
使用三目運算符
this.isSingleProductRedeemType && tips.push(<p>若部分取出,單產品贖回份額不少於1萬份</p>)
等價於
this.isSingleProductRedeemType ? tips.push(<p>若部分取出,單產品贖回份額不少於1萬份</p>) : null
列表渲染
get tipsRenders(): { render: () => VNode }[] {
const render = (jsx: VNode) => ({ render: () => jsx });
return this.tips.map(it => {
return typeof it === 'string' ? render(<span>{it}</span>) : render(it);
});
}
標籤屬性綁定
const href = 'https://devui.design/'
const element = <a href={href}>DevUI Design</a>
style樣式綁定
樣式綁定需使用雙大括號{{}}
const width = '100px'
const element = <button style={{ width, fontSize: '16px' }}></button>
事件綁定
事件綁定使用大括號{},事件名前需要加上on
前綴,
render(
<div class="state">
部分成交
<i
class="iconfont iconfont-info tip"
onClick={() => this.popTip(TradeSubdivisionState.partDeal)}
></i>
</div>
);
不帶參數時:
onClick={this.popTip}
事件修飾符
jsx中給事件增加修飾符需要藉助withModifiers
方法。
import { withModifiers, defineComponent, ref } from 'vue'
render(
<div class="state">
部分成交
<i
class="iconfont iconfont-info tip"
onClick={withModifiers(() => this.popTip(TradeSubdivisionState.partDeal), ['self'])}
></i>
</div>
);