父组件中form.getFieldDecorator包装了一个hooks子组件ChildComp:
import React, { useEffect } from 'react';
const ChildComp = (props) => {
// 这里参数要写多一个ref,否则还会多一个请确认ref参数是否使用的warning
const { value } = props;
return <input value={value} onChange={(e) => props.onChange(e.target.value)} />;
};
const Parent = props => {
const {
form: { getFieldDecorator }
} = props;
return (
<FormItem>
{getFieldDecorator('name',{})(<ChildComp {...props} />)}
</FormItem>
);
};
此时控制台会报错:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
解决方法: ant.design/components/…
修改代码如下:
import React, { useEffect, forwardRef } from 'react';
const ChildComp = (props, ref) => {
// 这里参数要写多一个ref,否则还会多一个请确认ref参数是否使用的warning
const { value } = props;
return <input value={value} onChange={(e) => props.onChange(e.target.value)} />;
};
const Child = forwardRef(ChildComp);
const Parent = props => {
const {
form: { getFieldDecorator }
} = props;
return (
<FormItem>
{getFieldDecorator('name',{})(<Child {...props} />)}
</FormItem>
);
};
另外如果父组件传值给子组件,如果项目中使用了react/prop-types eslint规则的话,会出现如下报错:
index.js:1446 Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
目前还未找到办法解决该问题(解决办法更新:使用typescript + hooks的方式可以避免该报错),由于该规则不能取掉,所以只好将hooks函数式组件改为class组件