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>
);
}
}
이 컴포넌트를 이렇게 사용하려고 하면
ReactDOM.render(<PageComponent />, document.getElementById("page"));
재산이라고 .foo 하다 요.기본값을 사용합니다.'어느새'를 써봤어요.static defaultProps = ...컴포넌트 안에 있었지만, 예상대로 효과가 없었습니다.
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
기본 속성 값을 사용하려면 어떻게 해야 합니까?우리 회사에서 사용하는 많은 JS 컴포넌트는 이 컴포넌트에 의존하고 있기 때문에 사용하지 않는 것은 선택사항이 아닙니다.
클래스 컴포넌트가 있는 기본 소품
「」를 사용합니다.static defaultProps 아닌.또한 소품 및 상태에는 클래스가 아닌 인터페이스를 사용해야 합니다.
2018/12/1 업데이트: : 、 TypeScript の 음음 to related related related related related related related related related related related 기능이 되었습니다.defaultProps및 문제까지 .최신 사용법부터 오래된 사용법 및 문제까지 자세히 읽어보십시오.
TypeScript 3.0 이후
TypeScript는 사용자가 원하는 대로 유형 검사를 수행할 수 있도록 특별히 지원을 추가했습니다.예:
interface PageProps {
foo: string;
bar: string;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, { this.props.foo.toUpperCase() }</span>
);
}
}
문자는 '어디서든'을하지 않고 및 컴파일할 수 .foo★★★★
<PageComponent bar={ "hello" } />
주의:
foo는 옵션 마크가 붙어 있지 않습니다(즉,foo?: stringJSX Attribute는 JSX Attribute입니다. 사항으로 표시한다는 은 ' 사항'이 될 수 을 의미합니다.undefined는 결코 것이다.undefineddefaultProps에 기본값을 나타냅니다.함수 파라미터를 옵션 또는 디폴트값으로 마킹하는 방법과 비슷하지만 둘 다 콜이 값을 지정할 필요는 없습니다.TypeScript 3.0+ 처리defaultProps리액트 유저에게 있어서, 같은 방법으로 매우 멋집니다.defaultProps에는 명시적 유형 주석이 없습니다.이 타입은 컴파일러에 의해 어떤 JSX 속성이 필요한지 판단하기 위해 추론되어 사용됩니다. 하면 .defaultProps: Pick<PageProps, "foo">defaultProps- matches--------- of의 서브셋과PageProps이 경고에 대한 자세한 내용은 여기를 참조하십시오.- 에는 「」가 필요합니다.
@types/react」16.4.11올바르게 동작합니다.
TypeScript 2.1~3.0의 경우
3.0 에서는 TypeScript 3.0에 대한 되었습니다.defaultProps할 수 시 하지만, 때만을 고려했기 에는 "Respect"를 "%"로? §:
interface PageProps {
foo?: string;
bar: number;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps: Partial<PageProps> = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, world</span>
);
}
}
주의:
- 을 달면 것 같아요.
defaultPropsPartial<>따라서 소품에 대해 타이핑할 수 있지만 모든 필수 속성을 기본 값으로 지정할 필요는 없습니다. 필수 속성은 기본값이 필요하지 않으므로 이는 의미가 없습니다. - 「」를 사용하고
strictNullChecks의 의 값this.props.foo되다possibly undefined, 논설)이 합니다.this.props.foo!(즉, "타입 가드입니다.if (this.props.foo) ...undefined디폴트 프롭 값은 실제로는 정의되지 않는다는 것을 의미하기 때문에 번거롭지만 TS는 이 흐름을 알 수 없습니다.3.이 TS 3.0에 한 주된 중 입니다.defaultProps.
TypeScript 2.1 이전 버전
'이렇게 하다'가 요.Partial 타입은 .Partial<>필요한 모든 소품에 기본값을 제공하거나(기본값이 사용되지 않더라도), 명시적 유형 주석을 완전히 생략합니다.
기능 컴포넌트가 포함된 기본 소품
하시면 됩니다.defaultProps되지만, 해야 합니다.다만, 기능을 입력해 주세요.FunctionComponent )StatelessComponent@types/react '' 이전'16.7.2가 TypeScript를 하도록 인터페이스를 defaultProps다음 중 하나:
interface PageProps {
foo?: string;
bar: number;
}
const PageComponent: FunctionComponent<PageProps> = (props) => {
return (
<span>Hello, {props.foo}, {props.bar}</span>
);
};
PageComponent.defaultProps = {
foo: "default"
};
굳이 하지 않아도 .Partial<PageProps>FunctionComponent.defaultProps 2.1 로 .
의 좋은 은 당신의 것을 이다.props파라미터를 지정하고 기본값을 직접 할당합니다.
const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
return (
<span>Hello, {foo}, {bar}</span>
);
};
'아예는 필요 없어요.defaultProps전혀!만약 제공한다면,defaultProps에서는 React는 으로 "Default 에 React는 값보다 우선합니다. 왜냐하면 React는 항상 명시적으로 다음을 통과하기 때문입니다.defaultProps 않기 되지 않습니다).values(파라미터는 정의되어 있지 않습니다).둘 다 말고 둘 중 하나를 사용하세요.
Typescript 2.1+ 에서는 인터페이스 속성을 옵션으로 하는 대신 Partial < T > 를 사용합니다.
export interface Props {
obj: Model,
a: boolean
b: boolean
}
public static defaultProps: Partial<Props> = {
a: true
};
기능 컴포넌트
실제로 기능 컴포넌트의 베스트 프랙티스는 다음과 같습니다.Spinner 컴포넌트의 샘플을 작성하겠습니다.
import React from 'react';
import { ActivityIndicator } from 'react-native';
import { colors } from 'helpers/theme';
export interface SpinnerProps {
color?: string;
size?: 'small' | 'large' | 1 | 0;
animating?: boolean;
hidesWhenStopped?: boolean;
}
const Spinner = ({
color = colors.primary,
size = 'small',
animating = true,
hidesWhenStopped = true,
}: SpinnerProps): JSX.Element => (
<ActivityIndicator
color={color}
size={size}
animating={animating}
hidesWhenStopped={hidesWhenStopped}
/>
);
export default Spinner;
이 있는 children사용하는 것이 더 나을 것이다React.FC음음음같 뭇매하다
export interface TypographyProps {
color?: string;
}
const Typography: React.FC<TypographyProps> = ({
children,
color,
}) => (
<span style={{ color }}>
{children}
</span>
);
export default Typography;
확산 연산자를 사용하여 표준 기능 구성요소로 소품을 다시 지정할 수 있습니다.이 접근법이 마음에 드는 점은 필요한 소품과 기본값이 있는 옵션 소품을 혼합할 수 있다는 것입니다.
interface MyProps {
text: string;
optionalText?: string;
}
const defaultProps = {
optionalText = "foo";
}
const MyComponent = (props: MyProps) => {
props = { ...defaultProps, ...props }
}
Typescript 3.0에서는 이 문제에 대한 새로운 해결 방법이 있습니다.
export interface Props {
name: string;
}
export class Greet extends React.Component<Props> {
render() {
const { name } = this.props;
return <div>Hello ${name.toUpperCase()}!</div>;
}
static defaultProps = { name: "world"};
}
// Type-checks! No type assertions needed!
let el = <Greet />
는 새로운 의 이 기능이 합니다.@types/react16.4.6와 함께 동작합니다.16.4.11.
승인된 답변에 대한 @pamelus의 코멘트:
모든 인터페이스 속성을 옵션(bad)으로 하거나 모든 필수 필드(불필요한 보일러 플레이트)에 기본값을 지정하거나 defaultProps에서 유형을 지정하지 않도록 해야 합니다.
실제로 Typescript의 인터페이스 상속을 사용할 수 있습니다.그 결과 코드는 조금 더 상세하게 나타납니다.
interface OptionalGoogleAdsProps {
format?: string;
className?: string;
style?: any;
scriptSrc?: string
}
interface GoogleAdsProps extends OptionalGoogleAdsProps {
client: string;
slot: string;
}
/**
* Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
*/
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
public static defaultProps: OptionalGoogleAdsProps = {
format: "auto",
style: { display: 'block' },
scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
};
디폴트값이 필요한 옵션 소품을 가지고 계신 분들에게 적합합니다.크레딧은 이쪽:)
interface Props {
firstName: string;
lastName?: string;
}
interface DefaultProps {
lastName: string;
}
type PropsWithDefaults = Props & DefaultProps;
export class User extends React.Component<Props> {
public static defaultProps: DefaultProps = {
lastName: 'None',
}
public render () {
const { firstName, lastName } = this.props as PropsWithDefaults;
return (
<div>{firstName} {lastName}</div>
)
}
}
기능적인 컴포넌트를 위해서, 나는 차라리 그 컴포넌트를 유지하고 싶다.props그래서 제 해결책은 다음과 같습니다.
interface Props {
foo: string;
bar?: number;
}
// IMPORTANT!, defaultProps is of type {bar: number} rather than Partial<Props>!
const defaultProps = {
bar: 1
}
// externalProps is of type Props
const FooComponent = exposedProps => {
// props works like type Required<Props> now!
const props = Object.assign(defaultProps, exposedProps);
return ...
}
FooComponent.defaultProps = defaultProps;
★★★★★★★★★★★★★★★★ optional ★★★★★★★★★★★★★★★★★」default4.4 이상:
export const LoadingSpinner = ({
size = "lg",
children,
}: {
size?: "sm" | "base" | "lg";
children?: any;
}) => {
console.log(size);
return <div>{children}</div>
};
다음과 같이 사용합니다.
<LoadingSpinner size="sm"><p>hello</p></LoadingSpinner>
<LoadingSpinner><p>hello</p></LoadingSpinner>
후크(타입 스크립트 포함)
export interface ApprovalRejectModalProps{
singleFileApprove:boolean;
}
ApproveRejectModal.defaultProps={
singleFileApprove:false --> default value
}
export const ApproveRejectModal:React.FC<ApprovalRejectModalProps>=(props)=>{
return (
<div>
....
</div>
)
}
솔루션 확인:
interface Props {
foo?: string | undefined;
bar: string;
other?: string;
}
export const Component = ({foo, bar, other = 'default text'}:Props) => {
console.log(foo, bar, other);
return(
...//some cool stuff your component should do
)
}
<Component bar='obligatory text'/>
언급URL : https://stackoverflow.com/questions/37282159/default-property-value-in-react-component-using-typescript
'programing' 카테고리의 다른 글
| 로컬 mongo db를 시작/시작할 수 없습니다. (0) | 2023.03.13 |
|---|---|
| 127.0.0.1:27017에 연결하지 못했습니다. 이유: errno:111 연결이 거부되었습니다. (0) | 2023.03.13 |
| Python/Django: 유닛 테스트 결과에 특정 문자열이 포함되어 있다고 단언하려면 어떻게 해야 합니까? (0) | 2023.03.13 |
| jquery에서 appendTo를 사용하는 올바른 방법 (0) | 2023.03.13 |
| ReactJS chrome 확장이 설치되었지만 표시되지 않음 (0) | 2023.03.13 |