react 第一节

58 阅读1分钟

jsx 编译

  • elment => babel =>React.createElement => VDOM {} diff VDOM2 => ReactDOM.render(VDOM,'ROOT') =>生成真实的DOM

JSX props & state写法  函数式组件 class 类组件函数式组件 组件首字母大写 function Welcome(props){ return

hello,{props.name}

} 类组件 class Welcome extends React.Component{ render(){ return

hello,{props.name}

}} 渲染 ReactDOM.render(Welcome,document.getElementById('root'))

super(props) --- 继承react.component 的所有特性

this.setState({date: new Date()}) ---- 修改state 数据

constructor ---- componentWillmount --- componentDidMount --- componentUnmout

16.8 ---  react hooks 方式开发  useState  数据管理    useEffect 数据监听 useMemo 数据缓存  useCallBack 事件缓存  ---- 只需要监听数据本身

react 是合成事件:

1. 进行了浏览器兼容 实现更好的跨平台 抹平不同浏览器的差异

2.避免垃圾回收 事件池

3. 方便事件统一管理

与原生事件区别

事件名称命名方式不同  --- 采用小驼峰 onClick

<button onclick = "handleClick()"></button> 原生DOM
const handleClick = (e) =>{
    console.log(e.nativeEvent) //获取DOM事件
}
//React
<button onClick = "{handleClick}"></button>

事件处理函数写法不同

阻止默认行为方式不同  原生 return false  preventDefault()无需调用addEventListener

绑定this 指向

  • this.handleClick = this.handleClick.bind(this); 
  • onClick = {()=>this.handleClick()} 

参数 

箭头函数要显式绑定

非箭头函数中隐式绑定

条件渲染

三元运算   if ... else   &&

如何阻止组件渲染

if(!props.warn){return}

key 值得唯一性 :  

  • diff算法更精准  
  • 防止页面混乱

map 方法循环遍历

 refs:  允许访问DOM节点

<p ref="{this.pRef}"></p>
const pNode = this.pRef.current;
pNode.textContent = '通过Refs操作添加的文本'

react脚手架 搭建框架

npx create-react-app my-app
cd my-app
npm start
npm run eject --- 提取webpack 脚本

app.js

import React from "react";class App extends React.Component {  constructor (props) {    super(props);    this.state = {      username: "test",      isShow:true    }  this.pRef = React.createRef(); //通过refs 添加文本  }  onChange (e) {    console.log(e.target.value);    this.setState({      username: e.target.value,      isShow:!this.state.isShow    })  }  onClickEvent = ()=>{ //箭头函数替代 this.onclickEvent.bind(this)      const prefVnode = this.pRef.current;      console.log(this.pRef)      prefVnode.textContent = '通过refs添加文本'  }  render () {    const isShowText = this.state.isShow;    return (    <div>      <p ref={this.pRef}></p>      <input name="username" value={this.state.username} onChange={(e) => this.onChange(e)} />      {        isShowText ? <span>{this.state.username}</span> :<span></span>      }    <button onClick={this.onClickEvent}>点击</button>    </div>    )  }}export default App;

state 的操作是 只render 修改部分

immutable.js   ==== vue loadsh 提供深拷贝 浅拷贝

Immer  和 immutable类似 但比immutable简单  只有一个produce api