const NameInput = xxxxx? A: B
<Form.Item label="用户名">
{getFieldDecorator('userName', {
rules: [{required: true, message: '请输入用户名'}]
})(<NameInput />)}
</Form.Item>
在一定条件下,A可能换成B组件,A为class声明的组件,B为函数式组件,但是切换成B组件后,发现无法输入,并且报错如下

猜测可能是切换后无法找到实例?一看这个ReactClassComponent.getRules,问题是B是用函数式组件写的,所以解决方案是
- 用class声明的写法重写B组件
- 或者给B包裹一层forwardRef, 把ref传递过去
方法2写法
B的组件代码原先是这样的
const B = props =>{
// 一堆逻辑xxxxxx
return (
<div>xxxxxxxxxxx</div>
)
}
用了forwardRef后是这样的
const B = React.forwardRef((props, ref)=>{
// 原先的逻辑和代码xxxx
return (
<div ref={ref}>xxxxx</div>
)
})
网友评论