PureComponent
如果父组件的属性和状态发生改变,默认情况下,子组件也要重新渲染
如果组件继承了PureComponent,react自身判断依赖的值有没有发生改变,如果没有发生改变,就不会重新渲染
类组件可以通过PureComponent提升性能
PureComponent判断如果render中的值没有发生改变就不会重新渲染,就像console.log,始终都是在打印一个值,没有发生变化,就不会在打印
class Child extends PureComponent {
render() {
console.log('ssss');
return (
<Fragment>
child
</Fragment>
)
}
}
PUureComponent里如果接收到的属性或者是更改后的状态和原属性、原状态相同的话,就不会去重新render了
在里面也可以使用·shouldComponentUpdate·,而且是否重新渲染,以shouldComponentUpdate的返回值作为最终的决定的因素,因为权重更高一点
refs
首先需要导入
``javascript
import React, { Component, createRef } from 'react'
export default class App extends Component {
div = createRef()
fn = createRef()
childned = createRef()
render() {
return (
<div>
<div ref = { this.div }> 你好</div>
{/* 函数组件不能使用createref,获取不到值 */}
{/* <Fn ref = { this.fn }> 你好</Fn> */} {/**报错 */}
<Chlidn ref = { this.childned }> 你好</Chlidn>
</div>
) }}
函数式组件是不能使用refs的,会报错,获取到的值是一个未定义的
类组件是可以使用的
vue中的ref
尽管存在prop和事件,有的时候你仍可能需要在JavaScript里直接访问一个子组件,为了达到这个目的,你可以通过ref这个attribute为子组件赋予一个id引用,例如:
<base-input ref="usernameInput"></base-input>
现在可以定义了这个ref的组件里,你可以直接使用:
this.$refs.usernameInput
进行获取组件中的值,但是从安全角度来考虑,这种方法不是很推荐,因为太过霸道,不需要任何访问,直接获取值
react中父组件给子组件传值
在父组件调用子组件的地方,添加自定义的属性,属性的值就是需要传递给子组件的值,如果属性的值是变量:boolean类型,number类型,对象,数组,函数,null,undfined,使用{}包裹
子组件是类组件和函数式组件的共同之处
1、验证传递的数据的数据类型,需要使用第三方模块props-types
com.propTypes = { 自定义的属性名: propTypes.数据类型}
2、如果属性的值是必传项
com.propTypes = { 自定义的属性名:PropTpyes.数据类型.isRequired}
3、如果属性的值是多只数据类型
com.propTypes = { 自定义的属性名:PropTypes。oneOfType([
PeopTyoes.属性类型1,PropType.数据类型2])}
4、如果子组件是类组件
如果需要设置默认属性的默认值,通过在类中,使用static,defaultProps = { 属性:属性值 }
4、如果子组件是函数式组件
如果需要设置属性的默认值,com.defaultProps = {属性:属性值}
function Title (props) {
return (
<h1>
标题 -- { props.name }
</h1>
)}
class Content extends Component {
render (){
return (
<section>
内容 - { this.props.name }
</section>
)}}
export default class App extends Component {
render() {
return (
<>
<Title name= 'title'></Title>
<Content name= 'content'></Content>
</>
)}}
类式组件使用this.props.name获取父组件的值
函数式组件使用props.name获取父组件的值
子组件给父组件传值
父组件在调用子组件的地方,添加一个自定义的属性,属性的值是一个函数,函数的默认参数就是子组件需要传递给父组件的值。
在子组件的某一个事件内部,通过this.props.自定义的事件属性(参数)或者peops,自定义的事件属性(参数)完成传值
子组件
render () {
return (
<>
<h1>标题 - { this.props.name } </h1>
<button onClick = { () => {
将值传入给fn里面
this.props.fn(this.state.num)
}}>发送阅读量给父组件</button>
</>)}
父组件
state={
sun:''
}
此时的getData中就有值了
getData = (val) => {
console.log(val);
this.setState({
sun : val
})
}
render() {
return (
<>
给父组件定义一个方法
<Title name= 'title' fn = { this.getData }></Title>
{this.state.sun}
</>)}
react中的逐层传递
父组件
render() {
return (
<>
<First name= ' 康娜给你啦 '></First>
</>)}
子组件
const Second = (props) => {
return (
<div>
22222
<Title name= { props.name }></Title>
</div>)}
class First extends Component {
render () {
return (
<div>
111
<Second name= { this.props.name }></Second>
</div>)}}
class Title extends Component {
render () {
return (
<>
33333 - { this.props.name }
</>)}}
如果中间有其他组件时,需要把值传递给最后一个子组件,就需要使用this.props.name一层一层传递下去