1. 程式人生 > >轉載--父元件呼叫子元件方法

轉載--父元件呼叫子元件方法

import React, {Component} from 'react';

export default class Parent extends Component {
    render() {
        return(
            <div>
                <Child onRef={this.onRef} />
                <button onClick={this.click} >click</button>
            </div>
        )
    }

    onRef = (ref) => {
        this.child = ref
    }

    click = (e) => {
        this.child.myName()
    }

}

class Child extends Component {
    componentDidMount(){
        this.props.onRef(this)
    }

    myName = () => alert('xiaohesong')

    render() {
        return ('woqu')
    }
}
 // this.refs.getStaffName.validateStaffName(e);
    // this.refs.getSex.validateSex();
    // this.refs.getTelNumber.validateTel();
    // this.refs.getIdNumber.validateId();
    // this.refs.getDepartment.validateDepartment();
    // this.refs.getHouseHold.validateHouseHold();
  };

  render() {
    return (
      <form action="" id="information">
        <ul>
        <InputText title="員工姓名" name="staffName"  id="staffName" msgId="staffNameMsg" reg={nameReg} helper="輸入長度在2-4" getFlag={flag=>this.getFlagName(flag)}/>
          <Sex
          getFlagSex={flagSex => {
              this.getFlagSex(flagSex);
            }}
            ref="getSex"
          />