安装
npx create-react-app my-app
启动
npm strat
react jsx
入口
index.js
react 原生对象
引入方式
import React form "react"
用React 创建一个节点,它是一个普通JS对象,用来描述真实元素
React.createElement("h1"null,“hell”)
有三个参数:1.节点类型,2.状态3.文本
react DOM
引入方式
import ReactDOM form "react-dom"
让虚拟节点显现出来
ReatctDOM.render(创建的点,docummet.querySelecotor("#root"))
组件化
创建组件两种方式,class类组件和函数式组件
类组件
calss Counter extends React.Component{
render(){
return
}
}
ReactDOM.reandr(,docummet.querySelecotor("#root"))
函数组件
组件的本地状态
状态的方法 this.setState({
count: this.state.count
})
function Counter(){
render(){
state= {count:2}
return
}
}
ReactDOM.reandr(,docummet.querySelecotor("#root"))
key 遵守两个原则:稳定,唯一
steat 组件内部状态,本地状态MVC,M(model模型state)V (view视图组件的结构) C(Conteoller控制器操作状态的方法
)
生命周期
生命周期
分为三个阶段
挂载时 更新时 卸载时
挂载阶段
开始的时候
constructor()
演升
static getDerivedStateFromProps(
return()
)
有两个参数 props state
在render()调用之后拿到真实节点在被调用
componentDidMount()
挂载阶段
先开始
static getDerivedStateFromProps(
return()
)
有两个参数 props state
在render()调用之后拿到真实节点在被调用
componentDidMount()
然后执行
shouldComponentUpdate(
有两个参数 nextProps, nextState
如果你一定要手动编写此函数,可以将 this.props
与 nextProps
以及 this.state
与nextState
进行比较,并返回 false
以告知 React 可以跳过更新。请注意,返回 false
并不会阻止子组件在 state 更改时重新渲染
return true 执行 render()
return false 终止更新
)
卸载阶段
componentWillUnmount()
用这个来清理内部数据
使用方法
先引用真实节点 react-DOM
然后在按钮上用reactDOM.unmountComponentAtNode(节点)
unmountComponentAtNode 这个方法 卸载节点方法
复用状态
实例
外层容器
export default class extends React.Component {
state = {
count: 0
}
static defaultProps = {
render() {}
}
add = () => {
this.setState({ count: this.state.count + 1 })
}
mima = () => {
this.setState({ count: this.state.count - 1 })
}
//返回值返回的的参数
render() { return this.props.render({ state: this.state, add: this.add, mima: this.mima }) }
}
外部的两个
第一个
export default class extends React.Component {
static defaultProps = {
count: 0,
add() { },
mima() { }
}
render() {
const { count, add, mima } = this.props
return (
{count}
增加
减少
)
}
}
第二个
export default class extends React.Component {
static defaultProps = {
count: 0,
add() { },
mima() { }
}
render() {
const { count, add, mima } = this.props
return (
{count}
+
-
)
}
}