Front-end/react/2.jsx.md

107 lines
2.6 KiB
Markdown
Raw Permalink Normal View History

2023-10-19 02:19:45 -04:00
# createElement
劣势
1. 繁琐不简洁
2. 不直观,不能一眼看出代码表述
3. 不优雅,用户体验差
# jsx
语法与html类似
JSX 是JavaScript XML的简写,表示在JavaScript代码中写xml(html)格式的代码.React的核心内容
优势:声明式语法更加直观,与html结构相同,降低成本,提高开发效率
React完全利用js语言自身能力来编写UI,而不是造轮子增强HTML功能(没有自定义指令).
```html
import React from 'react';
import ReactDOM from 'react-dom';
// const title = React.createElement('p',{title:"我是段落",id:"p1"},'hello xian',React.createElement('span',null,'hello hua'))
// jsx
const title = <p title='我是段落' id='p1'>hello xian<span>hello hua</span></p>
ReactDOM.render(title,document.getElementById('root'))
```
# 脚手架中使用jsx语法
1. JSX不是标准的ECMAScript语法,是他的拓展
2. 需要使用babel(@babel/preset-react)编译后,才能在浏览器中使用
3. create-react-app脚手架中已经默认有了该配置无需配置.
# 基本用法
1. 使用驼峰命名规则
2. 特殊的属性名 class->className,for->htmlFor,tabindex->tabIndex
3. 没有子节点可以使用/结尾
4. 推荐在小括号内写JSX
```html
const title = (<p className='title' title='我是段落' id='p1'>hello xian<span>hello hua</span></p>)
```
### 嵌入js
{JavaScript表达式}
```html
const name = "----------------------------"
const title = (<p className='title' title='我是段落' id='p1'>hello xian {name}<span>hello hua</span></p>)
```
### jsx条件渲染
根据条件渲染特定的jsx结构
if else ,三目,逻辑与运算符
```html
const isLoading = false
const loadData= ()=>{
// if(isLoading){
// return <div>loading...</div>
// }
// return <div>数据加载完成,此处显示加载后的数据</div>
// return isLoading?(<div>loading...</div>):(<div>数据加载完成,此处显示加载后的数据</div>)
return isLoading && (<div>loading...</div>)
}
const title = (
<h1>
条件渲染{loadData()}
</h1>
)
```
### jsx 列表渲染
```html
const songs = [
{id:1,name:'有为歌'},
{id:2,name:'水手'},
{id:3,name:'都是月亮惹的祸'}
]
const list = (
<ul>
{songs.map(item=><li key={item.id}>{item.name}</li>)}
</ul>
)
ReactDOM.render(list,document.getElementById('root'))
```
### jsx的样式处理
#### 行内样式 style
```html
const listStyle = (
<h1 style={{color:'red',backgroundColor:'skyblue'}}>行内样式</h1>
<h1 className = "title">类样式</h1>
)
```
#### 类名 className
```html
import './index.css'
const listStyle = (
<h1 className = "title">类样式</h1>
)
```
css
```html
.title{
text-align: center;
}
```