react 监听props变化


新建 forum.jsx 父组件。

import React from 'react';
import ForumDetail from './forumDetail';

export default class Forum extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 1
    };
  }
  render() {
    return (
      <div>
        <ForumDetail value={this.state.type} />
      </div>
    )
  }
}

新建 forumDetail.jsx 子组件。

import React from 'react';

export default class Forum extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: ''
    };
  }
  render() {
    return (
      <div>
        {`父组件传过来的值${this.state.type}`}
      </div>
    )
  }
  // 获取父组件传过来的值,这里还可以监听父组件传值变了,然后重新赋值给 state。
  // props 表示父组件传过来的值, state 表示当前子组件的state。
  static getDerivedStateFromProps(props,state) {

    // 父组件传过来的 type 和 子组件的 type 不一样,那么子组件重新赋值。
    // 也可以理解成,父组件传过来的值变了。
    if (props.type !== state.type) {
      // 这里执行相应的方法
      // console.log(123);
      return {
        type,//把父组件最新的props.type重新赋值到 子组件state.type 
      }
    }
    // 父组件的值没有变化,这里不做任何操作。
    return null
  }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM