react 入门
recat 安装
npm install creat-react-app -g
这里直接安装react的一个脚手架工具,里面包含了要用的很多东西,帮助快速入门recat
创建新项目
- create-react-app my-app
- cd my-app
- npm start
用脚手架创建一个新的单页应用,进到项目里面后start跑起来
react组件
- 引入Component组件
- JSX语法
- 渲染虚拟DOM
- 组件props
- 组件state
- 组件嵌套
- 组件生命周期
组件总览
首先在头部引入Component组件,然后通过class方式继承Component,最后将组件导出即可成为单独组件使用。需要注意的地方就是首字母一定要大写
//引入Component
import {Component} from 'react';
//首字母大写
class MyComponent extends Compomemt{
consturin(props){
super(props);
this.state={
isShow:true
}
}
//react 生命周期函数
componentWillMount(){}
componentDidMount(){}
componentWillReceiveProps(){}
shouldComponentUpdate(){}
componentWillUpdate(){}
componentDidUpdate(){}
componentWillUnMount(){}
//通过render函数可以将JSX语法渲染成真是dom
render() {
retrun (
<div>
<h1>我是组件</h1>
<p>{this.props.test}</p>
<button onClick = {()=>{
this.setState({
isShow : !this.state.isShow,
})
}}>点我</button>
<p>{this.state.isShow}</p>
</div>
)
}
}
//首字母大写
class Parent extends Component{
return <MyComponent test = '我是props'/>
}
export default Parent;
JSX语法
其实说白了就是html标签写到js中去,然后通过babel转移成react虚拟DOM对象,然后再渲染。
上例中
render(){
return (
<div>我是组件,{this.props.test}</div>
)
}
其实用的就是JSX语法,那么在标签内可以嵌套js语句。想要嵌套js语句时候需要用 { } 包起来。
渲染虚拟dom
关于这一点,要详细说起来还挺长的。考虑到是入门教程,于是乎我们就记住一点,当修改值需要react重新渲染的时候,react的机制是不会让他全部重新渲染的,它只会把你修改值所在的dom重新更新。这也是为什么react性能快的一大原因。这个选择渲染dom的算法叫做diff算法,如果要学习react就不能把这个给忘记。在日后需要好好把这方面的知识补全。这里还要补充的就是,react把JSX语法先转成react对象,然后通过内部创建节点插入到dom当中。还是考虑到快速,所以该节篇幅就不继续展开了,这些知识日后需要好好补全
组件props
props 如果接触过vue的话,应该很好理解这个概念,没接触过也不要紧,因为是比较容易上手的。我们这么理解,其实就是父组件给子组件的一些东西可以是基本数据类型,也可以是引用数据类型,也就是说什么都可以传,子组件可以通过 this.props这个对象看来获取父组件传下来的值
还是看上面的例子
class MyComponent extends Component{
render() {
//这里可以拿到
return (
<div>
<h1>我是组件</h1>
<p>{this.props.test}</p>
<button onClick={()=>{
this.setState({
isShow:!this.state.isShow,
})
}}>点我</button>
<p>{this.state.isShow}</p>
</div>
)
}
}
class Parent extends Component{
render() {
//通过父组件传进去
return <MyComponent test="我是props" />
}
}
组件state
组件state是状态,这里存放的就是该组件的一些会变化的变量,就是状态。比如判断组建数学变化,获取表单值等。修改state会引起react重新渲染。也就是更新状态会引起组件刷新。我们可以通过setState() 这个函数来设置state的值。不过要注意的是setState()这个函数是异步函数。下面还是看上面的例子
class MyComponent extends Component{
consturtion(props){
super(props);
this.state={
isShow:true
}
}
render() {
return (
<div>
<h1>我是组件</h1>
<p>{this.props.test}</p>
<button onClick={()=>{
//点击后可修改state值
this.setState({
isShow:!this.state.isShow,
})
}}>点我</button>
<p>{this.state.isShow}</p>
</div>
)
}
}
组件的嵌套
这个意思实际上就是一个组件里面可以用别的组件的意思。因此你可以吧组件划分的比较细致。以便更多的复用。
class Parent extends Component{
render() {
//使用了MyComponent组件
return <MyComponent test="我是props" />
}
}
组件生命周期
-
componentWillMount() {}
组件挂载前 -
componentDidMount() {}
组件挂载完执行 -
componentWillReceiveProps() {}
组件更新数据时执行,props
、state
-
shouldComponentUpdate() {}
组件需要更新时执行 -
componentWillUpdate() {}
组件更新前执行 -
componentDidUpdate() {}
组件更新后执行 -
componentWillUnmount() {}
组件销毁前执行
下面一张图解释生命周期