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

React class 父组件调用子组件的方法

作者: w晚风 | 来源:发表于2021-06-07 22:12 被阅读0次

    16.3.0之前的设置方法为

    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)的设置方法为

    父组件:

    import React, {Component} from 'react';
    import Demo2 from '../../component/Demo2/index';
    
    export default class Parent extends Component {
        onRef = (ref:any) => {
            (this as any).child = ref
        }
    
        // 点击调用子字符方法
        click = (e:any) => {
            (this as any).child.Fns();
        }
    
        render() {
            return(
                <div>
                    <button onClick = {this.click} >click</button>
                    <Demo2 onRef = {this.onRef}></Demo2>
                </div>
            )
        }
    }
    

    子组件

    import React, {Component} from 'react';
    
    export default class index extends Component {
        componentDidMount(){
            (this as any).props.onRef(this)
        }
    
        Fns = ()=>{
            console.log('我是子组件,我被父组件调用了')
        }
    
        render() {
            return(
                <div>
                    子组件呀
                </div>
            )
        }
    }
    

    相关文章

      网友评论

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

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