本人的React学习笔记分类(也是对应本人技术成长过程):[
想快速入门看这部分]、[想对React系统全面进行学习的同学看这里]、[对基础学习完成且有了一定开发经验,想尝试解析源码的看这里]
一、生命周期
生命周期即是组件从实例化到渲染到最终的从页面销毁,整个过程就是生命周期,在这个生命周期中,我们有许多可以调用的事件,也俗称为钩子函数
1、生命周期的三个状态:
- Mounting:将组件插入到DOM中
- Updating:将数据更新到DOM中
- Unmounting:将组件移除DOM中
2、生命周期中的钩子函数(方法、事件)
① CompontWillMount :组件将要渲染,AJAX,添加动画前的类
② CompontDidMount:组件渲染完毕,添加动画
③ componentWillReceiveProps:组件将要接受props数据,查看接收props的数据什么
④ ShouldComponentUpdate:组件接收到新的state或者props,判断是否更新。返回布尔值
⑤ CompontWillUpdate:组件将要更新
⑥ ComponentDidUpdate:组件已经更新
⑦ ComponentwillUnmount:组件将要卸载
import React,{Component} from 'react';import ReactDOM from 'react-dom';class ComLife extends Component{constructor(props){super(props)//调用继承Component的构造函数this.state = {msg:"hello world"}console.log("constructor构造函数")}componentWillMount(){console.log("componentWillMount组件将要渲染")}componentDidMount(){console.log("componentDidMount组件渲染完毕")}componentWillReceiveProps(){console.log("componentWillReceiveProps组件将要接收新的state和props")}shouldComponentUpdate(){//如果希望更新,就返回为真,不希望更新就返回为falseconsole.log("进行判断是否要更新内容")console.log(this.state.msg)if(this.state.msg==="hello world"){console.log(true)return true}else{console.log(false)return false}}componentWillUpdate(){console.log('componentWillUpdate组件将要更新')}componentDidUpdate(){console.log('componentDidUpdate组件更新完毕')}componentWillUnmount(){console.log('componentWillUnmount移除')}render(){console.log('render渲染函数')return (<div><h1>{this.state.msg}</h1><button onClick={this.changeMsg}>组件更新</button></div>)}changeMsg=()=>{this.setState({msg:"hello 老陈"})}}class ParentCom extends Component{constructor(props){super(props)this.state = {isShow:true}}render(){if(this.state.isShow){return (<div><button onClick={this.removeCom}>移除comlife</button><ComLife></ComLife></div>)}else{return <h1>将comlife已移除</h1>}}removeCom=()=>{this.setState({isShow:false})}}ReactDOM.render(<ParentCom></ParentCom>,document.querySelector('#root'))
二、表单输入
注意:必须绑定value和onChange事件
import React from 'react';class SearchCom extends React.Component{constructor(props){super(props)this.state = {value:"",result:null}}render(){return (<div><input type="text" placeholder="请输入查询的省份" onKeyDown={this.searchEvent} value={this.state.value} onChange={this.changeEvent} /><div><h2>查询结果:</h2><div>{this.state.result}</div></div></div>)}searchEvent=(e)=>{if(e.keyCode===13){console.log(e.keyCode)//当keycode是回车的时候在进行执行查询console.log(e.target.value)console.log(this.props.provincesObj[e.target.value])if(this.props.provincesObj[e.target.value]===undefined){this.setState({result:<h2>输入错误,不是省份。请输入正确的省份</h2>})}else{this.setState({result:(<div><div>确诊人数:{this.props.provincesObj[e.target.value].confirm}</div><div>死亡人数:{this.props.provincesObj[e.target.value].dead}</div><div>治愈人数:{this.props.provincesObj[e.target.value].heal}</div></div>)})}}}changeEvent=(e)=>{this.setState({value:e.target.value})}}export default SearchCom
