React组件介绍
React里面最小的单位:React元素/虚拟节点
在React中,有一个叫做组件的概念
组件化:页面划分的颗粒程度比模块化划分的更细。
创建组件的方法:class(类的继承):class app extends { };
2020.02.13
组件的两个核心概念:state和props
state:用来描述一个组件中的内部状态(动态数据)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9iexgbZG-1582465469233)(C:\Users\joey\AppData\Roaming\Typora\typora-user-images\image-20200213145958058.png)]
react会自己自动找到不同的节点,找到后重新渲染有改变的节点
举例:
import React from "react";
export default class Counter extends React.Component {
state = {
count: 0
};
render() {
return (
<div>
<p>
你一共点击了{this.state.count}次
</p>
//给button添加事件,用户点击加号count就加1,
<button
onClick={
()=>{
this.setState({
count:this.state.count+1
})
}
}
>+
</button>
</div >
)
}
}
只有函数才能产生作用域1
React.createRef( );方法,这个方法用来获取原生的节点
组件
组件可以分为无状态组件(stateless)和有状态组件(stateful)
Props 外部接口
react中组件的嵌套使用,会用到props
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qboqaiZj-1582465469235)(C:\Users\joey\AppData\Roaming\Typora\typora-user-images\image-20200222094530833.png)]
在react组件中给子组件接口,子组件拿到直接使用,注意为了避免出错,子组件的props要给上默认值
static defaultProps = {};//默认值,避免运行出错
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XXrmQD5F-1582465469245)(C:\Users\joey\AppData\Roaming\Typora\typora-user-images\image-20200222094727272.png)]
代码示例
import React from "react";//引入React以及自定义的两个组件
import Title from "./title"
import Ibutton from "./Ibutton"
export default class extends React.Component {
state = {//自定义count为1
count: 1
}
increase = () => {
this.setState({
count:this.state.count + 1 //count增加的方法
})
}
decrease = () => {
this.setState({
count:this.state.count - 1 //count减小的方法
})
}
render() {
return (
<div>
<Title count={this.state.count} /> //count接口把值暴露出去
<Ibutton name={"+"} onClick={this.increase} />
<Ibutton name={"-"} onClick={this.decrease} />
</div>
)
}
}
子组件Ibutton和Title
//title:
import React from "react";
export default class extends React.Component{
static defaultProps = { //定义默认值,避免出错,兼容性考虑
count:0
}
render(){
return (
<h1>{this.props.count}</h1>
)
}
}
//Ibutton:
import React from "react";
export default class extends React.Component{
static defaultProps = { //同样的定义默认值,避免出错,兼容性考虑
name:"55",
onClick:()=>{console.log("click")}
}
render(){
return (
<button onClick={this.props.onClick}>{this.props.name}</button>
)
}
}
pureComponent
React.PureComponent
React.PureComponent
与 React.Component
很相似。两者的区别在于 React.Component
并未实现 shouldComponentUpdate()
,而 React.PureComponent
中以浅层对比 prop 和 state 的方式来实现了该函数。
如果赋予 React 组件相同的 props 和 state,render()
函数会渲染相同的内容,那么在某些情况下使用 React.PureComponent
可提高性能。
注意
React.PureComponent
中的shouldComponentUpdate()
仅作对象的浅层比较。如果对象中包含复杂的数据结构,则有可能因为无法检查深层的差别,产生错误的比对结果。仅在你的 props 和 state 较为简单时,才使用React.PureComponent
,或者在深层数据结构发生变化时调用forceUpdate()
来确保组件被正确地更新
注:之前之所以让我们不要直接操作state里面的数据就是这个道理,是为了性能优化的。