父组件通过props将一个方法传进子组件中,子组件将要自己的this传出来,这样父组件就能拿到子组件的作用域了
把子组件的参数回传到父组件中,并且赋值给子组件的一个实例方法.
参考React中文网: http://www.css88.com/react/docs/refs-and-the-dom.html
- import React, {Component} from 'react';
- export default class Parent extends Component {
- render() {
- return(
- <div>
- <Child onRef={this.onRef} />
- <button onClick={this.click} >click</button>
- </div>
- )
- }
- onRef = (ref) => {
- this.child = ref
- }
- click = (e) => {
- this.child.myName()
- }
- }
- class Child extends Component {
componentDidMount(){
- //必须在这里声明,所以 ref 回调可以引用它
- this.props.onRef(this)
- }
- myName = () => alert('我的名字')
- render() {
- return ('lalalala')
- }
- }