react父子组件通信父传子、子传父

博客主要聚焦于React父子组件传参,暂不涉及理论知识,着重实现最基本的父子互传,并直接附上了父组件和子组件的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

理论性的知识咋们后期加,主要实现下最基本的父子互传。
直接附代码
父组件

import React, { Component } from 'react';
import Child from '../children';
export default class index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      visible: true
    };
  }
 
  handelClick() {
    console.log(this);
  }

  fn(data) {
    // console.log(data,'data');
    this.setState({
      count: data
    }, () => {
      console.log(this.state.count,'父组件');
    });
  }

  

  render() {
    return (
      <div style={{background:'green'}}>
        {this.state.count}
        父组件
        <Child count={this.state.count} pfn={this.fn.bind(this)}></Child>
        <button onClick={this.handelClick.bind(this)}>点击</button>
      </div>
    );
  }
}

子组件

import React, { Component } from 'react';

export default class index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      count: props.count
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.count !== prevState.count) {
      return {
        count: nextProps.count
      };
    }
    return null;
  }

  handleC(text) {
    // console.log(text);
    this.props.pfn(text);
  }

  render() {
    return (
      <div style={{border: 'solid 1px #ccc', margin: '0 20px'}}>
        这是子组件
        {this.state.count}
        <button style={{width:'200px', height:'100px'}} onClick={this.handleC.bind(this, 2)}>点击向父组件传递</button>
      </div>
    );
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值