两种方式创建Class组件
- ES5方式(过时)
import React from 'react';
const A = React.createClass({
render() {
return (
<div>hi</div>
)
}
})
export default A
// 由于 ES5 不支持 class, 才会有这种方式
复制代码
- ES6方式
import React from 'react';
class B extends React.Component {
constructor(props) {
super(props);
}
return() {
return (
<div> hi </div>
)
}
}
export defailt B;
// 有constructor 就一定要写super(),否则都别写。
复制代码
哪种好
- ES6 的 class 方式好
- 浏览器不支持ES6怎么办
用webpack + babel 将 ES6 翻译成 ES5 即可
如果面试的公司还在搞IE8 ,建议换一家
Props
- 传入props给B组件
class Parent extends React.Component {
constructor(props){
super(props)
this.state = {name:'frank'}
}
onClick = ()=>{}
return(){
return <B name={this.state.name}
onClick={this.onClick}>hi</B>
}
}
// 外部数据被包装为一个对象
// {name:'frank',onClick:...,children:'hi'}
// 此处的 onClick 是一个回调
复制代码
- 初始化
class B extends React.Component {
constructor(props) {
super(props);
}
render(){
}
复制代码
要么不初始化,即不写 constructor
要么初始化,且必须写全套(不写super直接报错)
-
效果
这么做了之后,this.props就是外部数据对象的地址了 -
读取
class B extends React.Component {
constructor(props) {
super(props);
}
render(){
return <div onClick={this.props.onClick}>
{this.props.name}
<div>
{this.props.children}
</div>
</div>
}
}
//通过 this.props.xxx 读取
复制代码
如何读props会了,那么如何写props呢?不准写props!!!!!!!!
写Props
- 改props的值(一个地址)
this.props={/另一个对象/}
不要写这样的代码,没有意义
理由:既然是外部的数据,就应该由外部更新 - 改props的属性
this.props.xxx=’hi’
不要写这样的代码,没有意义
理由: 既然是外部数据,就不应该从内部改值 - 原则
应该由数据的主人对数据进行更改
相关钩子
- componentWillReceiveProps钩子
当组件接受新的props时,会触发此钩子
啥是钩子?黑话,可以理解为【特殊函数】 - 该钩子已经被弃用
更名为UNSAFE_componentWillReceiveProps
总而言之,不要使用这个钩子 - 不使用,为什么还要写出来
因为这个钩子是以前推荐用的,了解这个是为了能看懂旧代码
Props的作用
- 接受外部数据
只能读不能写
外部数据由父组件传递 - 接受外部函数
在恰当的时机,调用该函数
该函数一般是父组件的函数
State & setState
初始化State
- 代码
class B extends React.Component{
constructor(props) {
super(props);
this.state = {
user: {name:'frank',age:18}
}
}
render() {/* ... */}
}
复制代码
读写State
- 读用 this.state
this.state.xxx.yyy.zzz - 写用 this.setState(???,fn)
this.setState(newState,fn)
注意setState不会立刻改变this.state,会在当前代码运行完后,再去更新this.state,从而触发UI更新
this.setState((state,props)=>newState,fn)
这种方式的state反而更易于理解
fn会在写入成功后执行 - 写时会 shallow merge
setState会自动将新state与旧state进行一级合并
不守规矩
- 修改this.state 的属性值
this.state.n+=1
this.setState(this.state)
不推荐用,但能用(因为React没法阻止你这么写)
......
本文为fjl的原创文章,著作权归本人和饥人谷所有,转载务必注明来源
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END