npm init -y
npm install vite
修改 package.json
脚本:
{
...
"scripts": {
"dev": "vite"
},
...,
"dependencies": {
"vite": "^3.1.6"
}
}
启动:
nmp run dev
> vite
# VITE v3.1.6 ready in 378 ms
# ➜ Local: <http://localhost:5173/>
# ➜ Network: use --host to expose
# 上午11:23:20 [vite] page reload index.html
创建 js/02.jsx
,修改 index.html
<!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>Learning React</title>
</head>
<body>
<div id="app"></div>
...
<!-- vite 支持 module -->
<script src="./js/02.jsx" type="module"></script>
</body>
</html>
class MyButton extends React.Component {
constructor(props) {
super(props);
this.state = {
openStatus: false,
};
}
statusChange() {
this.setState({
openStatus: !this.state.openStatus
})
}
render() {
// JSX 遵循JS的命名规范,一般使用camelCase小驼峰
// class => className tabindex => tabindex
return (
<div className='container'>
<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"));
为什么 React 不把视图标记和逻辑分开呢?