版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
前言:
|ू・ω・` ) 问题是这样的:
在子组件代码中将Form表单create了
之后在父组件中调用了子组件并增加了ref
可是我使用this.refs.子组件.某函数(),却找不到那个函数了
现在也百思不得其解,但是问题解决了,我是把子组件的函数直接暴露出来
解决方案:
/** 子组件 */
@Form.create()
class child extends Component {
constructor(props) {
super(props);
this.state = {},
};
props.childMethod(this.childMethod);//★★★★★将子组件定义的函数暴露出去
}
// 子组件定义的函数
childMethod= param => {
console.log("children")
};
render () {
const { form } = this.props;
return (
<Modal>
<Form>
<Form.Item labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} label="组织名称">
{form.getFieldDecorator('xxx')(<Input/>)}
</Form.Item>
</Form>
</Modal>
);
}
}
export default child;
/** 父组件 */
class father extends Component {
//调用子函数
triggerChild = () = > {
this.childMethod()//★★★★★因为子组件已将函数赋值给父,所以直接调用
//错误方案:this.refs.children.childMethod();
}
render () {
<child
ref='children'
childMethod={fn => {this.childMethod= fn}} //将子组件的函数赋给父,再调用时相当于调用父组件函数
></child>
}
}
问题是解决了,但是什么原因我还是半知半解,欢迎大佬前来赐教 Ψ( ̄∀ ̄)Ψ