當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
26 JSX深度剖析与使用技巧
生活随笔
收集整理的這篇文章主要介紹了
26 JSX深度剖析与使用技巧
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
React對JSX的處理
React.createElement有三個參數:標簽類型,屬性集合,子元素
JSX其實是React.createElement函數調用的語法糖
JSX → 編譯 → React.createElement調用形式
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判斷
總結
以上是生活随笔為你收集整理的26 JSX深度剖析与使用技巧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的大学生涯软件工程一年半
- 下一篇: 27 JSX函数子元素的应用与思考