클래스를 확장하여 리액트 컴포넌트를 만들 수 있으며 props와 state의 타입을 정할 수 있습니다. 특별한 타입이 없을 경우 아래오 같이 작성합니다. 만약, props와 state를 사용한다면 interface를 만들어서 원하는 타입 설정이 가능합니다.
export default class MyComponent extends React.Component<{}, {}> {
public render() {
return (
Hello World!
);
}
}
리액트에서 제공하는 propTypes를 사용할 수도 있지만, 타입스크립트의 interface를 적용하면 컴포넌트를 더욱더 깔끔하게 만들어 주며 코드의 가독성을 높여줍니다. 이는 객체 지향 프로그래밍(OOP) 언어인 Java, C# 등에서도 발견할 수 있습니다.
interface IMyComponentProps {
someDefaultValue: string
}
interface IMyComponentState {
someValue: string
}
export default class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
constructor(props : IMyComponentProps) {
super(props);
this.state = { someValue: this.props.someDefaultValue };
}
public render() {
return (
<div>
Value set as {this.state.someValue}
</div>
);
}
}
위 코드에서 someValue 값은 constructor 내부 state 객체에 정의되어 있으며 이는 값이 변경될 것을 알려줍니다. 만약 이 값이 변하는 값이 아니면 할당없이 render 내부에 바로 사용하면 됩니다. props는 불변의값(바뀌지 않음)이기 때문에 이것을 바꾸는 방법은 위와 같습니다.
Comments
Post a Comment