React
React脚手架的安装
npm i -g create-react-app
创建React项目
安装完成后可以创建React项目
# 项目名不要有大写
create-react-app 项目名
启动项目
想要开发项目需要启动
yarn start
npm start
类组件的形式
import React, {
Component } from "React";
class 组件名 extends Component {
constructor () {
// 继承属性,必须要添加
super()
// 固定写法,相当于vue的data
this.state = {
}
}
render () {
// 相当于Vue的template
return (
<div>
{
this.state.xxx}
</div>
)
}
}
export default 组件名
插值
class App extends Component {
constructor () {
super()
this.state = {
msg: "Hello React"
}
}
render () {
return (
// html代码
<div>
{
this.state.msg}
</div>
)
}
}
条件判断
条件判断用来在不同条件下,展示不同的HTML内容
class App extends Component {
constructor () {
super()
this.state = {
show: true
}
}
render () {
return (
<div>
{
this.state.show ? 如果为true时html结构 : 如果为false时HTML结构}
{
this.state.show
?
<div>true</div>
:
<div>false</div>
}
如果只有true没有false
{
this.state.show ? 如果为true时html结构 : null}
</div>
)
}
}
循环
import React, { Component } from 'react'
class App extends Component {
constructor () {
super()
this.state = {
stus: ["张三", "李四", "王五"]
/*
想要在页面上插入标签数组
我们只需要获取到一个数组中值都带标签即可
[
<li>张三</li>,
<li>张三</li>,
<li>张三</li>
]
*/
}
}
render () {
return (
<div>
<ul>
{
// 大括号中一定是数组
this.state.stus.map(
(stu, index) => <li key={index}>{stu}</li>
)
}
</ul>
</div>
)
}
}
事件绑定
在react中如果要绑定事件,直接在标签上添加on事件类型=“函数.bind(this)”
import React, { Component } from 'react'
class App extends Component {
constructor () {
super()
this.state = {
}
}
// 相关事件直接作为类的方法写到这里
clickHandler (形参, 事件对象) {
// 在函数中如果有参数,则在bind时,从第二个参数开始进行传参(因为第一个参数是this),最后一个没有传实参的参数就是事件对象
/*
fn (a,b,e) {}
this.fn.bind(this, a的参数, b的参数)
*/
}
clickHandler2 () {
}
// render函数
render () {
return (
<div>
<button onClick={this.clickHandler.bind(this, "实参")}>点击事件</button>
</div>
)
}
}
export default App
事件函数中修改state
import React, { Component } from 'react'
class App extends Component {
constructor () {
super()
this.state = {
msg: "Hello React"
}
}
// 相关事件直接作为类的方法写到这里
clickHandler () {
// 如果要设置相关的state 使用
this.setState({
msg: "修改后的值"
})
}
clickHandler2 () {
}
// render函数
redenr () {
return (
<div>
<button onClick={this.clickHandler.bind(this)}>点击事件</button>
</div>
)
}
}
export default App
模拟数据双向绑定
在React中数据是单向流,只能由state流向页面,页面的改变不会让state改变,因此在表单的绑定上需要模拟双向绑定
import React, {Component} from 'react'
class App extends Component {
constructor () {
super()
this.state = {
value:
}
}
change (e) {
this.setState({
value: e.target.value
})
}
render () {
return (
<div>
{/* 如果只是写value 那么键盘输入是没有任何反应的 还需要配合onChange使用 */}
<input value={this.state.value} onChange={this.change}>
</div>
)
}
}