【问题标题】:React props validation within return在返回中反应道具验证
【发布时间】:2020-01-02 05:11:09
【问题描述】:

我收到来自 es-lint 的警告,告诉我在 props 验证中缺少一些 props,但问题是我无法使其工作,因为它在 return 语句中。 我有以下代码,我从中删除了一些对此事不重要的部分,并且会使其变得不必要的大。

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

const ColumnSearch = () => {
     // few general functions

    return {
        filterDropdown: ({
            confirm,
        }) => (
            <div >
                // some general code for inputs and buttons
            </div>
        ),
        render: text => (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text}
            />
        ),
    };
};

export default ColumnSearch;

es-lint 告诉我

'confirm' is missing in props validationeslint(react/prop-types)

然后,我试过了:

ColumnSearch.propTypes = {
    confirm: PropTypes.func.isRequired,
};

ColumnSearch.propTypes = {
    filterDropdown: PropTypes.shape({
        confirm: PropTypes.func.isRequired,
    }).isRequired,
};

filterDropdown.propTypes = {
    confirm: PropTypes.func.isRequired,
};

但它们都没有奏效,后者告诉我:

'filterDropdown' is not defined.eslint(no-undef)

如何验证此道具?我认为简单地使用不是一个好主意:

/* eslint-disable react/prop-types */

编辑:

我用这段代码创建了一个沙盒:

CodeSandbox

【问题讨论】:

  • 组件是如何使用的?
  • 这是来自 ant-design ant.design/components/table/… 的搜索函数,函数 getColumnSearchProps 但它使用单个类组件,我将其转换为无状态组件。我还将它提取到一个名为 ColumnSearch 的外部文件中。我删除了其余的代码,因为它只是关于按钮和通用功能。

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


【解决方案1】:

你应该声明 confirm 属性,试试这个。

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

const ColumnSearch = ({confirm}) => { //declare here
     // few general functions

    return {
        filterDropdown: ({
            confirm,
        }) => (
            <div >
                // some general code for inputs and buttons
            </div>
        ),
        render: text => (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text}
            />
        ),
    };
};

export default ColumnSearch;

ColumnSearch.propTypes = {
    confirm: PropTypes.func.isRequired,
};

【讨论】:

  • 它不起作用:/它说:'confirm' is already declared in the upper scope.eslint(no-shadow) 所以我将它从较低的范围中删除,然后它只是说confirm is not a function
  • 如何使用组件 来自父母?您应该将一个函数传递给 ColumnSearch 的确认道具
  • codesandbox.io/s/wispy-cookies-id7ou 这就是我拥有的代码以及它的使用方式。寻找 ColumnSearch.jsx,这就是问题所在。不过,我无法在 codesanbox 中重现 es-lint 错误。
猜你喜欢
  • 1970-01-01
  • 2017-09-26
  • 2022-01-27
  • 2021-09-29
  • 1970-01-01
  • 2018-03-05
  • 2018-06-14
  • 2017-06-20
  • 2017-06-21
相关资源
最近更新 更多