반응형
TypeScript에서 React 구성 요소 확장
TypeScript에서 React.js를 사용하고 있습니다.다른 구성 요소에서 상속되지만 몇 가지 추가적인 요소/상태를 갖는 React 구성 요소를 만들 수 있는 방법이 있습니까?
제가 달성하고자 하는 것은 다음과 같습니다.
interface BaseStates {
a: number;
}
class GenericBase<S extends BaseStates> extends React.Component<void, S> {
protected getBaseInitialState(): BaseStates {
return { a: 3 };
}
}
class Base extends GenericBase<BaseStates> {
getInitialState(): BaseStates {
return super.getBaseInitialState();
}
}
interface DerivedStates extends BaseStates {
b: number;
}
class Derived extends GenericBase<DerivedStates> {
getInitialState(): DerivedStates {
var initialStates = super.getBaseInitialState() as DerivedStates; // unsafe??
initialStates.b = 4;
return initialStates
}
}
하지만, 제가 전화를 걸면 이것은 실패할 것입니다.this.setState
에Derived
TypeScript 오류(유형 매개 변수)가 표시됩니다.DerivedStates
유형에 할당할 수 없습니다.S
). 이것은 TypeScript에 특화된 것이 아니라 상속과 제네릭(?)을 혼합하는 것에 대한 일반적인 제한이라고 생각합니다.이것에 대한 안전한 해결책이 있습니까?
갱신하다
제가 결정한 해결책(David Sherret의 답변에 기초함):
interface BaseStates {
a: number;
}
class GenericBase<S extends BaseStates> extends React.Component<void, S> {
constructor() {
super();
this.state = this.getInitialState();
}
getInitialState(): S {
return { a: 3 } as S;
}
update() {
this.setState({ a: 7 } as S);
}
}
interface DerivedStates extends BaseStates {
b: number;
}
class Derived extends GenericBase<DerivedStates> {
getInitialState(): DerivedStates {
var initialStates = super.getInitialState();
initialStates.b = 4;
return initialStates;
}
update() {
this.setState({ a: 7, b: 4 });
}
}
에서 한 번에 몇 가지 상태 속성만 설정할 수 있습니다.Derived
형식 어설션을 사용하여:
this.setState({ b: 4 } as DerivedStates); // do this
this.setState({ a: 7 } as DerivedStates); // or this
this.setState({ a: 7, b: 4 }); // or this
그건 그렇고, 다른 이름을 가질 필요는 없습니다.getInitialState
당신은 그냥 할 수 있습니다:
class GenericBase<S extends BaseStates> extends React.Component<void, S> {
constructor() {
super();
this.state = this.getInitialState();
}
protected getInitialState() {
return { a: 3 } as BaseStates as S;
}
}
class Derived extends GenericBase<DerivedStates> {
getInitialState() {
var initialStates = super.getInitialState();
initialStates.b = 4;
return initialStates;
}
}
import { Component } from 'react'
abstract class TestComponent<P = {}, S = {}, SS = any> extends Component<P, S, SS> {
abstract test(): string
}
type Props = {
first: string,
last: string,
}
type State = {
fullName: string,
}
class MyTest extends TestComponent<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
fullName: `${props.first} ${props.last}`
}
}
test() {
const { fullName } = this.state
return fullName
}
}
언급URL : https://stackoverflow.com/questions/32866534/extending-react-components-in-typescript
반응형
'code' 카테고리의 다른 글
탐색 컨트롤러 스택, 하위 뷰 또는 모달 컨트롤러를 사용하지 않고도 컨트롤러를 신속하게 변경할 수 있습니까? (0) | 2023.06.12 |
---|---|
PHP의 "비개체에 대한 속성 가져오기 시도" (0) | 2023.06.12 |
C의 2D 배열 포인터 (0) | 2023.06.12 |
C 스타일 언어에서 익명 {}개 블록의 목적은 무엇입니까? (0) | 2023.06.12 |
선형 회귀 분석 및 R 단위로 그룹화 (0) | 2023.06.12 |