相关疑难解决方法(0)

使用TypeScript在React组件中的默认属性值

我无法弄清楚如何使用Typescript为我的组件设置默认属性值.

这是源代码:

class PageState
{
}

export class PageProps
{
    foo: string = "bar";
}

export class PageComponent extends React.Component<PageProps, PageState>
{
    public render(): JSX.Element
    {
        return (
            <span>Hello, world</span>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用这样的组件时:

ReactDOM.render(<PageComponent />, document.getElementById("page"));
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,说财产foo缺失.我想使用默认值.我也尝试static defaultProps = ...在组件内部使用,但它没有像我怀疑的那样有效.

src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
Run Code Online (Sandbox Code Playgroud)

我如何使用默认属性值?我公司使用的许多JS组件都依赖于它们而不使用它们不是一种选择.

typescript reactjs tsx

123
推荐指数
7
解决办法
7万
查看次数

propType "name" 不是必需的,但没有相应的 defaultProps 声明

我有一个带有可选道具的组件。我通过将可选属性传递给 Card 组件来定义它们的默认值,但 eslint 一直告诉我propType "text" is not required, but has no corresponding defaultProps declaration.属性也是如此childrenwithout defaultProps下面的代码似乎与本页上的示例一致: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-default-props.md

import { ReactElement } from 'react';

interface CardProps {
  title: string,
  text?: string | (string|ReactElement)[],   // eslint is complaining here
  children?: React.ReactNode                 // and here
}

const Card = ({ title, text = '', children = null }: CardProps) => (
    <div className="container">
      <div className="title">{title}</div>
      <div className="underline" />
      <div className="card">
        <div className="text">
          {text}
          {children}
        </div>
      </div> …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

reactjs ×2

typescript ×2

tsx ×1