基础
混合js和html语法格式
1.返回的时候必须是一个根节点
2.class类名,要写成className
3.{}执行js代码
4.样式会自动的展开
5.数组里面可以执行html标签
- 例如 let arr[<p>啦啦</p>,...]
6.注释{/注释内容/}
组件
js组件 class组件 function组件
=== class组件
import React,{Component} from 'react'
export default class Child extends Component{
render(){ return (<div>{this.props.children}</div>)}
}
=== function组件
function MyTag({children}){
return (<h1>函数组件{children}</h1>)
}
当导入组件时,只填写文件,会自动去查找文件夹index.js
state和props区别
state和props主要的区别在于props是不可变的,而state可以根据与用户交互来改变。这就是为什么有些容器组件需要定义state来更新和修改数据。而
子组件只能通过props来传递数据。
props
1.props的默认值设置:
Child.defaultProps= {age:20}
2.props参数传入:
<Child age="30">
3.props参数使用:
在child使用{this.props.age}
4.props属性只读不修改
state状态
1.初始:
constructor(props){ super(props); this.state={name:"han",age:18} }
2.使用:
{this.state.age}
3.更新:
this.setState({age:80})
更新state dom节点也会更新
表单数据绑定和双向绑定
<input balue={this.state.msg} onChange={e=>{this.setState({msg:e.target.value})}}>
函数组件与class组件区别:
函数组件没有state,也没有this;
react如何响应事件
1.事件驼峰式:onClick
onChange
2.事件中的this:
onclick={()=>{this.showMsg()}}
修改事件方法中的this指向;
onclick={this.showMsg.bind(this)}
修改this
默认事件中的this为当前的元素
生命周期钩子函数
定义:react组件从创建到销毁 更新都会有一系列的回调函数,我们把这些回调函数,称为生命周期钩子函数;
- constructor 组件的构造器
- componentWillMount 组件即将渲染
- render 渲染 多次
- componentDidMount 组件已经渲染,可以启用ajax请求,启用定时器
- componentWillUnmount 组件即将卸载,可以销毁定时器
- componentWillUpdate 组件即将更新
- componentDidUpdate 组件已经更新