VSCode 插件推荐
Hello React
原生JS实现
原生JS是命令式编程
<body>
<h1 class="msg"></h1>
<button class="btn">切换</button>
<script>
const msg = document.querySelector('.msg')
msg.innerHTML = 'hello world'
const btn = document.querySelector('.btn')
btn.addEventListener('click', () => {
msg.innerHTML = 'hello react'
})
</script>
</body>
React实现
react是声明式编程
- 必须引入3个依赖(官方文档)
- react: 包含react必须的核心代码
- react-dom: 用于在不同平台渲染
- babel: 将 JSX 转译为 react.createElement
- script标签必须加 type=”text/babel” 才能使用 JSX 语法
reactDOM.render(参数1:要渲染的内容,参数2:要挂载到的对象)
<body>
<div id="app"></div>
<!-- 必须引入3个依赖 -->
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- 必须加 type="text/babel" -->
<script type="text/babel">
let message = 'hello world'
const changeMsg = () => {
message = 'hello react'
render() // 需要手动重新渲染
}
const render = () => {
ReactDOM.render(
<div>
<h1>{message}</h1>
<button className="btn" onClick={changeMsg}>切换</button>
</div>,
document.getElementById('app'))
}
render()
</script>
</body>
React组件化
点击事件默认调用是
fn.apply(undefined)
, 所以必须bind(this)
<body>
<div id="app"></div>
<!-- 必须引入3个依赖 -->
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- 必须加 type="text/babel" -->
<script type="text/babel">
class App extends React.Component {
constructor(){
super()
this.state = {
message: 'hello world'
}
}
changeMsg(){
this.setState({
message: 'hello react'
})
}
render(){
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={this.changeMsg.bind(this)}>切换</button>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector('#app'))
</script>
</body>