react 父组件获取子组件,调用子组件的方法

父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React from 'react';
import Tabs from './tabs';
 
export default class FruitsList extends React.Component {
 
  constructor(props) {
    super(props);
 
    this.state = {
      child: '',
    }
  }
  child() {
    this.child.Alert(value)
  }
 
  // 子组件调用父组件的 setChild 方法,传入this( this就是子组件 ),保存到父组件的state里面
  setChild(that) {
    this.setState({
      child: that
    })
  }
 
  render() {
    return (
      <div>
        <Tabs setChild={this.setChild}></Tabs>
        <button onClick={this.child.bind(this)}></button>
      </div>)
  }
}

  

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React from 'react';
 
export default class Tabs extends React.Component {
 
  Alert() {
    alert("子组件的Alert方法调用")
  }
 
  //组件完成挂载调用父组件传过来的 setChildren(this) 这里的this 指向 Tabs 组件
  componentDidMount() {
    this.props.setChild(this);
  }
  render() {
    return (<div>
      我是子组件
    </div>);
  }
}

  

 

posted @   男孩亮亮  阅读(717)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示