为了账号安全,请及时绑定邮箱和手机立即绑定

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()
    }

}

子组件:

export default class ParentComponent extends Component {
    componentDidMount(){
        this.props.onRefChild(this)
    }

    childMethods = () => alert('子组件被执行了')

    render() {
        return (<div>我是子组件</div>)
    }

}

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

父组件:

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 { 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);
点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消