加载中...
  • React class 父组件调用子组件的方法

    16.3.0之前的设置方法为

    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
    var HelloMessage = React.createClass({
    childMethod: function(){
    alert("组件之间通信成功");
    },
    render: function() {
    return <div> <h1>Hello {this.props.name}</h1> <button onClick={this.childMethod}>子组件</button></div>
    }
    });

    // 父组件
    var ImDaddyComponent = React.createClass({
    getDS: function(){
    // 调用组件进行通信
    this.refs.getSwordButton.childMethod();
    },
    render: function(){
    return (
    <div>
    <HelloMessage name="John" ref="getSwordButton" />
    <button onClick={this.getDS}>父组件</button>
    </div>
    );
    }
    });

    ReactDOM.render(
    <ImDaddyComponent />,
    document.getElementById('correspond')
    );

    16.3.0之后(包括16.3.0 version)的设置方法为

    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
    32
    33
    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(){
    this.props.onRef(this)
    }

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

    render() {
    return ('woqu')
    }
    }
    上一篇:
    子组件调用父组件方法
    下一篇:
    React中 JSX防踩坑的几个地方
    本文目录
    本文目录