zoukankan      html  css  js  c++  java
  • React父组件调用子组件

    通点击父组件按钮调用子组件的方法

    父组件:

    import React, {Component} from 'react';
    import ChildComponent from './child';
    export default class ParentComponent extends Component {
        render() {
            return(
                <div>
                    <ChildComponent onRefChild={this.onRefChild} />
                    <button onClick={this.clickParent.bind(this)} >{'点击'}</button>
                </div>
            )
        }
    
        onRefChild = (ref) => {
            this.child = ref
        }
    
        clickParent = (e) => {
            this.child.childMethods()
        }
    
    }

    子组件:

    import React, {Component} from 'react';
    export default class ParentComponent extends Component {
        componentDidMount(){
            this.props.onRefChild(this)
        }
    
        childMethods = () => alert('子组件被执行了')
    
        render() {
            return (<div>我是子组件</div>)
        }
    
    }

     另外一种情况,子组件使用了 'rc-form';

    父组件:

    import React from 'react';
    import ChildComponent from './child'
    class Index extends React.Component {
        startCreat = () => {
            // 获取到子组件的值
            let values = this[`formRef`].getItemsValue();
        }
        render(){
            return (
                <div>
                    <ChildComponent wrappedComponentRef={(form) => this[`formRef`] = form}/>
                    <button onClick={this.startCreat.bind(this)}>{'点击获取子组件值'}</button>
                </div>
            )
        }
    }
    export default Index;

    子组件:

    import React from 'react';
    import { createForm } from 'rc-form';
    class ChildComponent extends React.Component {
        // 父组件获取form内值
        getItemsValue = () => {
            const values= this.props.form.getFieldsValue(); 
            return values;
        }
        render(){
            const { getFieldProps } = this.props.form;
            return (
                <div
                    {...getFieldProps('key',{
                        initialValue: 1
                })}
                >
                </div>
            )
            
        }
    }
    export default createForm()(ChildComponent);
  • 相关阅读:
    codeforces 图论题目集(持续更新)
    整数快速幂
    Codeforces Codeforces Global Round 5 C2
    POJ 1061
    扩展欧几里德算法(数论)
    Codeforces Round #592 (Div. 2) 1224D
    Codeforces Round #582 (Div. 3) G. Path Queries
    2019 kickstart A轮 B 题
    P3379 【模板】最近公共祖先(LCA)
    bzoj 2002 分块
  • 原文地址:https://www.cnblogs.com/0828-li/p/11011601.html
Copyright © 2011-2022 走看看