React父组件向子组件传值

目录

需求

代码实现

父组件

子组件


需求

首先,在父组件中,我想点击按钮触发事件调用方法去setState值,因为值变了所以引发子组件重新刷新加载,在子组件中检查传递给子组件的属性是否发生变化,并根据需要执行操作。

代码实现

父组件

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cityName: 'New York',
    };
  }

  handleChangeCity = (newCityName) => {
    this.setState({ cityName: newCityName });
  };

  render() {
    return (
      <div>
        <button onClick={() => this.handleChangeCity('London')}>
          Change City to London
        </button>
        <ChildComponent cityName={this.state.cityName} />
      </div>
    );
  }
}

子组件

class ChildComponent extends Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      cityName: '',
    };
  }

  componentWillReceiveProps(nextProps: any) {
    // 检查传递给子组件的属性是否发生变化,并根据需要执行操作
    alert(nextProps.cityName);
    if (this.props.cityName !== nextProps.cityName) {
      alert('City Name has changed');
    }
  }

  render() {
    return null; // 或其他组件的渲染内容
  }
}

相关推荐

  1. React组件组件

    2024-01-18 07:12:02       39 阅读
  2. uniapp组件组件

    2024-01-18 07:12:02       43 阅读
  3. Vue实现组件组件

    2024-01-18 07:12:02       18 阅读
  4. VUE中组件组件进行

    2024-01-18 07:12:02       10 阅读
  5. 请说明Vue组件组件的方法

    2024-01-18 07:12:02       20 阅读
  6. 组件组件参的方式?

    2024-01-18 07:12:02       19 阅读
  7. vue3 组件组件

    2024-01-18 07:12:02       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-18 07:12:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-18 07:12:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-18 07:12:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-18 07:12:02       20 阅读

热门阅读

  1. 笨蛋学设计模式结构型模式-组合模式【12】

    2024-01-18 07:12:02       28 阅读
  2. MATLAB Fundamentals>>Representing Discrete Categories

    2024-01-18 07:12:02       35 阅读
  3. Hadoop之mapreduce参数大全-7

    2024-01-18 07:12:02       27 阅读
  4. flutter 播放SVGA动图

    2024-01-18 07:12:02       36 阅读
  5. Spring Boot整合Junit

    2024-01-18 07:12:02       27 阅读
  6. esp32-c-简单应用笔记

    2024-01-18 07:12:02       32 阅读
  7. 消息队列之RabbitMQ工作模式

    2024-01-18 07:12:02       32 阅读
  8. Spring Boot整合Junit,@RunWith和@SpringBootTest的使用

    2024-01-18 07:12:02       32 阅读
  9. LUA 对象转excel

    2024-01-18 07:12:02       31 阅读
  10. Bitcoin的Covenants——合同化管理UTXO的花费方式

    2024-01-18 07:12:02       46 阅读
  11. 在 Centos 7.9 中,安装与配置 Docker 20.10.18

    2024-01-18 07:12:02       32 阅读
  12. flask不使用flask-login插件

    2024-01-18 07:12:02       35 阅读