React父组件调用子组件

本文介绍如何在React中通过引用和回调实现父组件调用子组件方法及获取子组件值,适用于需要跨组件交互的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

父组件:

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);

 

转载于:https://www.cnblogs.com/0828-li/p/11011601.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值