美文网首页
父组件调用子组件的方法

父组件调用子组件的方法

作者: 懒懒猫 | 来源:发表于2022-02-22 16:01 被阅读0次

推荐把方法写到父组件里。子组件通过props调用,或父组件传值控制子组件调用
父,jsx

import React, { Component } from 'react';
import Child from '@/components/modal/CancelTestPlan'; //取消测试计划组件
class statistics extends Component {
    render() {
        //对state数据解构赋值
        
        return (
          <div>
          <Child onRef={this.onRef} />
          <button onClick={this.click} >click</button>
      </div>
        )
    }
    onRef = (ref) => {
      this.child = ref
  }

  click = (e) => {
      this.child.myName()
  }
}
export default statistics;

子.jsx

import React, { Component, useState } from 'react';

class Child extends Component {

  componentDidMount() {
    this.props.onRef(this)
  }

  myName = () => {
    alert('xiaohesong')
  }

  render() {
    return (
      <div>
        Open

      </div>
    )
  }
}

export default Child;

相关文章

网友评论

      本文标题:父组件调用子组件的方法

      本文链接:https://www.haomeiwen.com/subject/huiolrtx.html