【问题标题】:ESLint React PropTypes, 'prop' is missing in prop validationESLint React PropTypes,道具验证中缺少“道具”
【发布时间】:2018-08-01 03:17:59
【问题描述】:

我有一个无状态的反应组件

import React from 'react'
import styled from 'styled-components';
import PropTypes from 'prop-types';

export default props => <StyledButton>{props.children}</StyledButton>

StyledButton.propTypes = {
    children: PropTypes.node,
}
StyledButton.defaultProps = {
    children: null,
}

还有一个类组件

class Thumbnail extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
           color: 'red',
        }
    }
    render() {
        return (
           <button>{this.props.children}</button>
       )
    }
}

Thumbnail.propTypes = {
    children: PropTypes.node,
}
Thumbnail.defaultProps = {
    children: null,
}

我的 eslintrc 文件

module.exports = {
"extends": "airbnb",
"plugins": [
    "react",
    "jsx-a11y",
    "import"
],
"rules": {
    "react/jsx-filename-extension": 0,
    "semi": 0,
    "indent": ["error", 4],
    "react/jsx-indent": 0,
    "jsx-a11y/img-redundant-alt": 0
}
};

Eslint 抱怨无状态组件中的“道具验证中缺少孩子”。 但是在类组件中就可以了。

花了 2 个小时试图解决这个问题,任何帮助将不胜感激

【问题讨论】:

    标签: reactjs eslint react-proptypes eslint-config-airbnb


    【解决方案1】:

    这是因为您正在直接导出无状态组件而没有任何变量保存它,同时您正在为不存在的StyledButton 创建propTypesdefaultProps。试试这个。

    const StyledButton = props => <button>{props.children}</button>;
    
    StyledButton.propTypes = {
      children: PropTypes.node,
    };
    
    StyledButton.defaultProps = {
      children: null,
    };
    
    export default StyledButton;
    

    【讨论】:

    • @kevinjanada 我还建议不要在默认道具中使用 null ,而是使用空跨度。
    猜你喜欢
    • 2020-10-29
    • 2016-12-05
    • 2021-09-04
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2020-05-19
    • 1970-01-01
    相关资源
    最近更新 更多