React對JSX的處理
React.createElement
有三個參數:標簽類型,屬性集合,子元素
JSX其實是React.createElement
函數調用的語法糖
JSX → 編譯 →React.createElement
調用形式
class App extends React.Component {render() {return (<div className="box" id="J_Box"><h1 className="title">This is a <span>TITLE</span></h1></div>)}
}
ReactDOM.render(<App />,document.getElementById('app')
)
class App extends React.Component {render() {return /* @__PURE__ */ React.createElement("div", {className: "box",id: "J_Box"}, /* @__PURE__ */ React.createElement("h1", {className: "title"}, "This is a ", /* @__PURE__ */ React.createElement("span", null, "TITLE")));}
}
React元素類型
- MyButton → 是React元素 → 也是React元素類型
- 以JSX形式使用組件,則該組件必須存在于當前作用域
React.createElement
拿到組件并實例化,拿到他的視圖
如何在JSX中使用點語法
const colorSystem = {danger: 'red',info: 'gray',primary: 'blue',warning: 'orange'
}
const MyUI = {Button: class extends React.Component {render() {const { type, children } = this.propsreturn (<buttonstyle={{color: '#fff',backgroundColor: colorSystem[type]}}>{children}</button>)}}
}
class App extends React.Component {render() {return (<><MyUI.Button type="danger">Click</MyUI.Button><MyUI.Button type="info">Click</MyUI.Button><MyUI.Button type="primary">Click</MyUI.Button><MyUI.Button type="warning">Click</MyUI.Button></>)}
}
ReactDOM.render(<App />,document.getElementById('app')
)
class LoginBtnGroup extends React.Component {render() {return (<div><h1>請先登錄</h1></div>)}
}
class WelcomeInfo extends React.Component {render() {return (<div><h1>HI {this.props.username}</h1></div>)}
}
class Header extends React.Component {static componets = {'login': LoginBtnGroup,'welcome': WelcomeInfo}render() {const HeaderUser = Header.componets[this.props.type]return (<HeaderUser{...this.props} />)}
}
JSX的props
JS表達式與語句
- JSX大括號里可以傳入任何js表達式
- 但不可以傳入語句如if、for、switch、function,非表達式可以在JSX大括號外面使用(如render里、return外)
字符字面量
- 字符串字面量傳入的props能顯示特殊符號
- JS表達式方式傳入的props將原封不動的顯示
- 字符串傳入的意義是字符串本意,傳入了字符串
true
,不代表Bool真假,隱式轉換為真,但全等===true
判斷為假
authorShow ={ true }
JS表達式方式傳入的props,在語義和邏輯上都代表Bool真假
a=“1” // 字符串1
a={1} // 數字1
- 字符串字面量去除首位空格、換行
- 字符串之間多個空格壓縮為一個,加多個
$nbsp;
- 控制換行:
<br/>
- 要顯示
<>
,使用字符實體<
>
- 在JS表達式里
{'This is a <TITLE>'}
可以渲染出<>
剩余運算符
- 剩余運算符展開props
- 如果有不用的屬性,先行解構,再展開余下的屬性
const { a,...others } = this.props
返回一組JSX
子元素
- 與運算控制邏輯,0是會渲染的,因此不走&&之后
- 可以改為或運算
- 或用length === 0判斷