React 是 Facebook(现 Meta)于 2013 年开源的 JavaScript 库,用于构建用户界面,特别是单页应用。它专注于视图层,采用组件化开发模式,使用虚拟 DOM 提高渲染性能。React 已成为前端开发的主流框架之一。
React.createElement()useState - 状态管理useEffect - 副作用处理useContext - 上下文my-react-app/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── components/ # 组件目录
│ ├── pages/ # 页面组件
│ ├── hooks/ # 自定义 Hooks
│ ├── App.js # 根组件
│ ├── index.js # 入口文件
│ └── index.css # 全局样式
├── package.json
└── README.md
function Welcome(props) {
return <h1>Hello, {props.name}</h1>
}
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>
}
}
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
)
}
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>欢迎回来!</h1>
}
return <h1>请登录</h1>
}
function List({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)
}
const [state, setState] = useState(initialValue)
useEffect(() => {
// 副作用逻辑
return () => {
// 清理逻辑
}
}, [dependencies])
const value = useContext(MyContext)
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue)
const increment = () => setCount(count + 1)
return { count, increment }
}
# 使用 Create React App
npx create-react-app my-app
cd my-app
npm start
# 使用 Vite(推荐)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
npm run build
App.js
import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<div className="App">
<h1>React Demo</h1>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
)
}
export default App