JSX
基本使用
npx create-react-app 项目名称
或者npm init react-app 项目名称
- 在
src/index.js
文件中尝试输入以下内容
import React from 'react'
import ReactDOM from 'react-dom'
const title = (<h1>hello jsx</h1>)
ReactDOM.render(title, document.getElementById('root'))
- 在项目根目录使用
npm start
启动项目
注意
- 不推荐使用上面的
createElement
来创建节点, 推荐使用JSX
- 在使用
JSX
的时候, react 元素的属性名使用的是驼峰的命名, 特殊的属性名如下: - class -> className, for -> htmlFor, tabindex -> tabIndex
- 推荐使用小括号将 JSX 代码包括起来, 避免 JS 中自动插入分号的问题
- ● JSX 必须要有一个根节点, 和 vue2 一样, 如果不想有的话, 可以设置一个幽灵节点, 即
<></>
嵌入 JS 表达式
- 语法: { JS表达式 }
const name = 'xiaosheng'
const info = (<div>我叫{name}</div>)
条件渲染
const loading = true
const loadData = () => {
if (loading) {
return <div>loading...</div>
}
return <div>请求结束</div>
}
const data = (
<h1>
条件渲染
{loadData()}
</h1>
)
列表渲染
const languages = [
{
id: 1,
name: 'html'
},
{
id: 2,
name: 'css'
},
{
id: 3,
name: 'javascript'
}
]
const data = (
<ul>
{languages.map(item => {
return <li key={item.id}>{item.name}</li>
})}
</ul>
)
样式处理
添加行内样式
// 小驼峰命名
const data = (
<h1 style={{'color': 'red', 'backgroundColor': 'blue'}}>hello</h1>
)
添加类名
// 引入 css 文件
import './css/index.css'
const data = (
<h1 className='ceshi'>hello</h1>
)