1. 程式人生 > 其它 >React父元件呼叫子元件

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