我正在尝试在使用eslint和prop-types的项目中对按钮使用forwardRef。
这是我到目前为止尝试过的,并且每次都会遇到错误:
function Button ({ action = { callback: () => {}, title: 'unknown' } }, ref) {
return (<button ref={ref} onClick={action.callback} title={action.description} type="button">{action.icon || action.title}</button>)
}
Button.propTypes = {
action: Action.isRequired
}
export default forwardRef(Button)
这将在控制台中向我发出以下警告:Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
function ButtonFunction ({ action = { callback: () => {}, title: 'unknown' } }, ref) {
return (<button ref={ref} onClick={action.callback} title={action.description} type="button">{action.icon || action.title}</button>)
}
const Button = forwardRef(ButtonFunction);
Button.propTypes = {
action: Action.isRequired
}
export default ButtonFunction;
我得到:action is missing in props validation
。
const Button = forwardRef(({ action = { callback: () => {}, title: 'unknown' } }, ref) => {
return (<button ref={ref} onClick={action.callback} title={action.description} type="button">{action.icon || action.title}</button>)
});
Button.propTypes = {
action: Action.isRequired
}
export default Button;
这次,我得到:Component definition is missing display name
。
那么正确的方法是什么?
答案 0 :(得分:3)
const Form = React.forwardRef(function Form(
{ submitHandler, keyUpHandler, label, type, placeholder, buttonTxt },
ref
) {
export default Form
这样做没有警告。 function Form
负责处理名称。
答案 1 :(得分:0)
interface SomeProps {
// written your props
};
const SomeFC = forwardRef((props:SomeProps,ref)=>{
// do something and returns
}})
声明内部 FC 的 props 类型可以修复 proptypes 警告!