【问题标题】:Why is PropTypes throwing error in an internal function of a functional component?为什么 PropTypes 在功能组件的内部函数中抛出错误?
【发布时间】:2020-04-07 08:49:51
【问题描述】:

我已经定义了一个这样的无状态功能组件:

// a is a list of object, each having 'title' & 'subtitle' property
export const SampleComponent = ({a}) => {
    const internalFunction = ({ title, subtitle}) => {
        // return a jsx based on title and subtitle
        return;
    };
    return a && a.length && <div className='sampleComponent'>
        { a.map(item => internalFunction(item) }
    </div>
};

SampleComponent.propTypes = {
    a: PropTypes.object
};

但是当我在文件上运行 eslint 时,它会抛出如下错误:

error  'title' is missing in props validation     react/prop-types
error  'subtitle' is missing in props validation  react/prop-types

这些错误点的行号是我定义internalFunction的地方。 但我无法弄清楚为什么我会收到此错误,因为 titlesubtitle 不是我的 SampleComponentprops 的一部分。

【问题讨论】:

    标签: javascript reactjs eslint react-props react-component


    【解决方案1】:

    尝试将 proptypes 添加到内部组件。

    const internalFunction = ({ title, subtitle}) => {
        // return a jsx based on title and subtitle
        return;
    };
    internalFunction.propTypes = {
       title: PropTypes.string,
       subtitle: PropTypes.string
    };
    return a && a.length && <div className='sampleComponent'>
        { a.map(item => internalFunction(item) }
    </div>
    

    【讨论】:

    • 但为什么internalFunction 需要它?它不是一个需要定义自己的 props 的组件
    【解决方案2】:

    由于您在 props 中传递一个数组,因此编写 propType 的正确方法是

    SampleComponent.propTypes = {
        a: PropTypes.arrayOf(PropTypes.shape({
            title: PropTypes.string,
            subtitle: PropTypes.string
          }))
    };
    

    这应该可以解决 eslint 错误。

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2021-12-29
      • 2021-05-11
      • 2021-06-14
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多