## **JSX語法:**
**在JSX語法中,{}是js的運行環境**
**一:使用變量或者調用函數使用單括號**
```
render() {
return <p>hello { this.message }</p>
}
```
**二:使用組件,無需在components中定義,可以直接使用**
~~~
import MyComponent from './my-component'
export default {
render() {
return <MyComponent>hello</MyComponent>
},
}
~~~
**三:屬性和Props**
1.直接在標簽上面使用:
~~~
render() {
return <input type="email" />
}
~~~
2.使用變量:
~~~
render() {
return <input
type="email"
placeholder={this.placeholderText}
/>
}
~~~
3.使用對象的形式,需要配合對象的展開運算符`...`使用,注意對象需要符合渲染函數的`數據對象`
~~~
render() {
const inputAttrs = {
type: 'email',
placeholder: 'Enter your email'
}
return <input {...{ attrs: inputAttrs }} />
//渲染結果:<input type="email" placeholder="Enter your email">
}
~~~
**四:插槽**
1.具名插槽:
~~~
render() {
return (
<MyComponent>
<header slot="header">header</header>
<footer slot="footer">footer</footer>
</MyComponent>
)
}
~~~
2.作用域插槽:
~~~
render() {
const scopedSlots = {
header: () => <header>header</header>,
footer: () => <footer>footer</footer>
}
return <MyComponent scopedSlots={scopedSlots} />
}
~~~
**五:指令**
1. `v-model`雙向綁定
~~~
<input vModel={this.newTodoText} />
~~~
2.也可以直接使用`v-model`
```
<input v-model={this.value}></input>
```
3.帶有修飾符
~~~
<input vModel_trim={this.newTodoText} />
~~~
3.`v-html`
~~~
<p domPropsInnerHTML={html} />
~~~
**六:事件**
1.直接使用原生綁定`onClick`或者`onInput`,注意想要傳遞參數,請使用箭頭函數的形式。
```
<button onClick={()=>this.onclick(100)}>onClick </button>
```
2.`vON:事件名稱` 的形式綁定,但在編輯器中有錯誤警告。
~~~
<button vOn:click={()=>this.onclick(100)}>vOn </button>
~~~
3.使用對象的形式,需要配合對象的展開運算符`...`使用,注意對象需要符合渲染函數的`數據對象`
```
const on = {
click:()=>this.onclick(100)
}
return (
<div>
<button {...{ on }}>onClick </button>
</div>
)
```
4.使用事件修飾符
~~~
<input vOn:click_stop_prevent={this.newTodoText} />
~~~
#### **七:`v-if` 和`v-for`**
~~~
{/* 類似于v-if */}
{this.withTitle && <Title />}
{/* 類似于v-if 加 v-else */}
//使用三元運算符實現v-if
{this.isSubTitle ? <SubTitle /> : <Title />}
{/* 類似于v-for */}
//使用數組的map方法實現v-for
{this.options.map(option => {
<div>{option.title}</div>
})}
~~~
#### **八:樣式**
在JSX中可以直接使用`class="xx"`來指定樣式類,內聯樣式可以直接寫成`style="xxx"`
~~~
<div class="btn btn-default" style="font-size: 12px;">Button</div>
<!-- 動態指定 -->
<div class={`btn btn-${this.isDefault ? 'default' : ''}`}></div>
<div class={{'btn-default': this.isDefault, 'btn-primary': this.isPrimary}}></div>
<div style={{color: 'red', fontSize: '14px'}}></div>
~~~
>[success] 任意符合渲染函數的數據對象都可以直接寫在JSX的元素中,例如 `<a {...{ 數據對象 }}></a>`