生活随笔
收集整理的這篇文章主要介紹了
02 JSX学习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用vite處理jsx
vite引入的腳本必須是ESM的
npm init
-y
yarn add vite
package.json 添加vite命令
index
.html引入jsx
JSX是什么
一種標簽語法,在JS基礎上進行的語法擴展不是字符串、也不是HTML是描述UI呈現與交互的直觀的表現形式JSX被編譯后會生成React元素 (React.createElement的效果),是對象遵循JS的命名規范(小駝峰) class → className tabindex → tabIndex用插值表達式寫邏輯(綁定事件處理函數、顯示變量)單標簽必須閉合只能有一個根標簽
render之前發生了什么
所有JSX都會轉成字符串所有輸入的內容都會進行轉義 (避免XSS攻擊)
React元素
JSX經過內部轉換為React元素,和React.createElement()創建的元素相同
console.log(<h1 className
="test">123</h1
>)
React為什么不把視圖標記和邏輯分離
渲染和UI標記有邏輯耦合即使耦合,也能實現關注點分離
插值表達式
- 一切有效的,符合JS變成邏輯的表達式 { title }
- 引號表示的是字符串
修改state setState
this.setState({openStatus
: !this.state
.openStatus
})
class組件必須render并return
函數組件只return
相關代碼
{"name": "02","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "vite"},"keywords": [],"author": "","license": "ISC","dependencies": {"vite": "^2.5.10"}
}
<!DOCTYPE html
>
<html lang
="en"><head
><meta charset
="UTF-8"><meta http
-equiv
="X-UA-Compatible" content
="IE=edge"><meta name
="viewport" content
="width=device-width, initial-scale=1.0"><title
>REACT 01</title
><script crossorigin src
="https://unpkg.com/react@17/umd/react.development.js"></script
><script crossorigin src
="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script
>
</head
><body
><div id
="app"></div
><script src
="./index.jsx" type="module"></script
>
</body
></html
>
const el
= <div className
="title">JSX創建React元素
</div
>
ReactDOM
.render(el
, document
.getElementById('app')
)
class MyButton extends React.Component
{constructor(props
) {super(props
)this.state
= {openStatus
: true}}statusChange() {this.setState({openStatus
: !this.state
.openStatus
})}render() {return (<div className
="button_wrap"><p className
="text">{this.state
.openStatus
? '打開狀態' : '關閉狀態'}</p
><button onClick
={this.statusChange.bind(this)}>{this.state
.openStatus
? '去關閉' : '去打開'}</button
></div
>)}
}ReactDOM
.render(React
.createElement(MyButton
), document
.getElementById('app')
)
ReactDOM.render第一個參數
1. JSX
const oEl
= <h1
>test
</h1
>
ReactDOM
.render(oEl
,document
.getElementById('app')
)
2. 函數
function update() {return (<h1
>test
</h1
>)
}
ReactDOM
.render(update(),document
.getElementById('app')
)
function update() {const oEl
= <h1
>test
</h1
>ReactDOM
.render(oEl
,document
.getElementById('app'))
}
update()
3. 寫類組件
ReactDOM
.render(<MyButton
/>,document
.getElementById('app')
)
ReactDOM
.render(React
.createElement(MyButton
),document
.getElementById('app')
)
總結
以上是生活随笔為你收集整理的02 JSX学习的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。