'-6ren"> '-代码 import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps {-6ren">
gpt4 book ai didi

reactjs - 类型 'Requireable' 不可分配给类型 'Validator<"horizo​​ntal"| "vertical"| undefined>'

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:18 24 4
gpt4 key购买 nike

代码

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

interface ILayoutProps {
dir?: 'horizontal' | 'vertical'
};

const Layout: React.FunctionComponent<ILayoutProps> = (props) => {
return (
<div>
{props.children}
</div>
);
};

Layout.defaultProps = {
dir: 'horizontal'
};
Layout.propTypes = {
dir: PropTypes.oneOf(['horizontal', 'vertical'])
};
export default Layout;

错误信息

TS2322: Type '{ dir: Requireable<string>; }' is not assignable to type 'ValidationMap<ILayoutProps>'.
Types of property 'dir' are incompatible.
Type 'Requireable<string>' is not assignable to type 'Validator<"horizontal" | "vertical" | undefined>'.

我应该如何定义 Layout.propTypes?

最佳答案

创建一个新类型并引用它。

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

type Direction = 'horizontal' | 'vertical'

interface ILayoutProps {
dir?: Direction;
};

const Layout: React.FunctionComponent<ILayoutProps> = (props) => {
return (
<div>
{props.children}
</div>
);
};

Layout.defaultProps = {
dir: 'horizontal',
};

Layout.propTypes = {
dir: PropTypes.oneOf<Direction>(['horizontal', 'vertical']),
};

export default Layout;

我喜欢强类型的方式。你也可以考虑这个代码。

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

export enum Direction {
Horizontal = 'horizontal',
Vertical = 'vertical',
}

interface ILayoutProps {
dir?: Direction;
};

const Layout: React.FunctionComponent<ILayoutProps> = (props) => {
return (
<div>
{props.children}
</div>
);
};

Layout.defaultProps = {
dir: Direction.Horizontal,
};

Layout.propTypes = {
dir: PropTypes.oneOf<Direction>([
Direction.Horizontal,
Direction.Vertical,
]),
};

export default Layout;

用法:

import Layout, { Direction } from './Layout';
// ...
<Layout dir={Direction.Horizontal}></Layout>

关于reactjs - 类型 'Requireable<string>' 不可分配给类型 'Validator<"horizo​​ntal"| "vertical"| undefined>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53671306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com