子組件使用了 Form.create()如何讓父組件調用子組件的方法
在寫react技術棧使用ant design時 Form的使用會帶來一個問題,會導致你無法直接使用refs去調用使用Form的子組件自定義方法。當你調用時會拋出異常。
子組件寫有Form表單父組件使用this.refs.refName.mychild是獲取不到該方法的,要用wrappedComponentRef。
父組件:
export default class Parents extends Component{
constructor(props) {
super(props);
this.state = {}
}
getChildFun() {
this.formRef.childFun()
}
render() {
return{
<button onClick={this.getChildFun.bind(this)}>調用子組件的方法</button>
<div>
<Order wrappedComponentRef={(e) => this.formRef = e}/>
</div>
}
}
}
子組件
import { Form, InputNumber } from 'antd';
const FormItem = Form.Item;
export default class Order extends Component{
constructor(props) {
super(props);
this.state = {}
}
childFun() {
console.log("方法調用成功!")
}
render() {
return{
<div>
<Form>
<span>這是子組件!</span>
</Form>
</div>
}
}
}
Order = Form.create()(Order);