在父組件中,編寫以下:函數
類中定義child,用於存放子組件的做用域this
public child: any;Copy to clipboardErrorCopied
綁定子組件做用域spa
public onRef(ref:any){ this.child = ref }Copy to clipboardErrorCopied
子組件上綁定refcode
<ChildPage onRef={(el)=>this.onRef(el)} />Copy to clipboardErrorCopied
this.onRef = this.onRef.bind(this)Copy to clipboardErrorCopied
在子組件中,編寫以下:ip
constructor中onRef綁定this作用域
this.props.onRef(this)Copy to clipboardErrorCopied
完成以上4步驟,父組件中能夠隨便調用子組件中state的值以及方法。get
export class ParentCom extends React.Component<{}, {}> { constructor(props:{}){ super(props); this.onRef = this.onRef.bind(this); } public child: any; onRef(ref:any){ this.child = ref; } getChildFun(){ this.child.testFun(); } render(){ return ( <div> <span>父組件</span> <ChildCom onRef={this.onRef}></ChildCom> </div> ) } } interface childProps{ onRef? : any } export class ChildCom extends React.Component<childProps, {}> { constructor(props:{}){ super(props); this.props.onRef(this); } testFun(){ console.log(123) } render(){ return ( <div> <span>子組件</span> </div> ) } }