使用 prop-types 时检查对象中的键是否为字符串

check if the key in an object is string or not when using prop-types

我有以下道具需要检查

const columns = {
  name: {
    key    : 'company',
    label  : 'Company',
  },
  employee: {
    key  : 'employee',
    label: 'Employee',
  },
}

使用流程我会用下面的方式检查这个

[key: string]: { // the key is dynamic
      key: string,
      label?: string,
}

我如何在使用 prop-type 时进行此类检查?我对此很陌生。

更新

<Table
  isSearchable
  columns={columns}
  data={data}
/>

column 道具将始终是具有 key value 方法的对象,其中 key 应始终为字符串,value 应为 object of key(name) and label

可能是条款造成了混乱,所以我将列道具更新为

const columns = {
  name: { // how do i check name which is a key and is dynamic
    uniqueName    : 'company',
    displayName  : 'Company',
  },
  employee: {
    uniqueName  : 'employee',
    displayName: 'Employee',
  },
}

您可以将 PropTypes.shapePropTypes.oneOfType

一起使用
PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.shape({
    name: React.PropTypes.string.isRequired,
    label: React.PropTypes.string,
  }),
]);

查看this example

PropTypes 包假定道具已提前命名和已知。虽然在技术上可能可以检查 运行 对密钥的任意检查(我正在关注自定义验证器和这个 ),但我认为你 非常 困难时期。我想提出挑战并提出替代方案。

而不是传递一个看起来像这样的对象:

const columns = {
    name: {
        uniqueName    : 'company',
        displayName  : 'Company',
    },
    employee: {
        uniqueName  : 'employee',
        displayName: 'Employee',
    },
};

将列作为列数组传递。这里的好处是使用 PropTypes 检查非常简单,我想在代码中推理会更容易。

function App() {
    const columns = [
        {
            column: 'name',
            uniqueName: 'company',
            displayName  : 'Company',
        },
        {
            column: 'employee',
            uniqueName: 'employee',
            displayName  : 'Employee',
        },
    ];

    return (
        <Report
            columns={columns}
        />
  );
}
import React from 'react';
import PropTypes from 'prop-types';

function Report(props) {
    const { columns } = props;

    return (
        <div>
            {columns.map( (column) => {
                return (
                    <p key={column.column}>
                        {column.column}
                    </p>
                )
            })}
        </div>
    )
}

Report.propTypes = {
    columns : PropTypes.arrayOf(
        PropTypes.shape({
            column: PropTypes.string,
            uniqueName: PropTypes.string,
            displayName: PropTypes.string
        })
    )
};

export default Report;

在我自己的项目中,我会更进一步,使 Column 成为它自己的 class 并用 PropTypes.instanceOf:

检查它
const columns = [
    Column.init( { ... } ),
    Column.init( { ... } ),
]

... 

Report.propTypes = {
    columns : PropTypes.arrayOf(PropTypes.instanceOf(Column))
};