使用带有proptypes和eslint的forwardRef

时间:2020-01-13 11:52:14

标签: javascript reactjs eslint react-proptypes react-forwardref

我正在尝试在使用eslintprop-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

那么正确的方法是什么?

2 个答案:

答案 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 警告!