typescript 中的组件传值与调用

// 父组件
import React, {Component} from 'react';
class Parents extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }
    componentDidMount() {

    }
    
    handleCancel = (e) => {
        console.log('父组件的方法被子组件调用');
    }

    childClick = (e) => {
        this.child.onShow()
    }
    render() {
        return (
            <section>
                <Child onCancel={this.handleCancel} onRef={(ref)=>{ this.child = ref}}></Child>
                <div onClick={this.childClick}>调用子组件的函数</div>
            </section>
        );
    }
}

export default Parents;



// 子组件
import React, {Component} from 'react';
class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    componentDidMount() {
        this.props.onRef(this)
    }
    
    onShow(){
        console.log('子组件的方法被父组件调用')
    }

    render() {
        return (
            <section>
                <div onClick={()=>{this.props.handleCancel()}}>子组件用this.props调用父组件的函数</div>
            </section>
        );
    }
}

export default Child;

案例中的应用

子组件定义接口规则

interface AddPersonProps {
  [name: string]: any
}

在这里插入图片描述
若不定义使用接口规则会出现报错
在这里插入图片描述
同时也无法使用父组件传来的 值 与 方法
在这里插入图片描述
子组件中定义的方法,(需要在父组件调用的)

  // 显示添加人员弹窗
  public showModal = (record?) => {
    this.setState({
      visible: true,
      id: record.id,
      userName: record.user_name,
      subordinateBranch: record.subordinate_branch
    });
  };

子组件中的生命周期

  // 挂载
  public componentDidMount() {
    this.getOsintUser()
    // 在生命周期中,将自组件最高层级this当参数传出去
    this.props.onRef(this)
  }

父组件定义一个索引签名
在这里插入图片描述
若不定义索引签名,则无法在该父组件上随意添加所需的属性
添加后也无法使用,并报错
在这里插入图片描述
在这里插入图片描述
在快速修复中,会出现提供修复的方式,可以选择添加索引签名,系统会自动完成为父组件添加索引签名的这一步
在这里插入图片描述

父组件中调用子组件的方法

  // 编辑行
  public handleEdit = (record: string | number) => {
    console.log(record,'11111111');
    
    this.child.showModal(record)
  }

引入的子组件

<AddPerson list={this.getList} onRef={(ref)=> this.child = ref} />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值