Sha*_*oux 27 javascript reactjs eslint react-proptypes react-forwardref
我正在尝试使用eslint和prop-types在项目中将 forwardRef 用于 Button 。
这是我到目前为止所尝试的,以及我每次得到的错误:
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)
Run Code Online (Sandbox Code Playgroud)
这将在控制台中给我以下警告: 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;
Run Code Online (Sandbox Code Playgroud)
我得到: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;
Run Code Online (Sandbox Code Playgroud)
这一次,我得到:Component definition is missing display name。
那么这样做的正确方法是什么?
Jul*_*ent 42
您几乎完成了第三次尝试。但是您不必使用两次forwardRef,第一次使用Button声明就足够了。显示名称规则不是错误(无论是在 JavaScript 还是 React 级别),而是为了显示组件的“真实”名称,React 在调试消息中使用的故意道具。在您的情况下,该forwardRef函数将隐藏转译器的“真实”组件名称。
如果displayName为每种情况编写确实存在问题,您甚至可以禁用此规则。
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
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
}
Button.displayName = 'Button'
export default ButtonRun Code Online (Sandbox Code Playgroud)
const Form = React.forwardRef(function Form(
{ submitHandler, keyUpHandler, label, type, placeholder, buttonTxt },
ref
) {
Run Code Online (Sandbox Code Playgroud)
export default Form
这样做没有警告。function Form照顾这个名字。
| 归档时间: |
|
| 查看次数: |
14994 次 |
| 最近记录: |