跳至主要内容

类组件

在 TypeScript 中,React.Component 是一个泛型类型(即 React.Component<PropType, StateType>),因此您需要为其提供(可选的)prop 和 state 类型参数。

type MyProps = {
// using `interface` is also ok
message: string;
};
type MyState = {
count: number; // like this
};
class App extends React.Component<MyProps, MyState> {
state: MyState = {
// optional second annotation for better type inference
count: 0,
};
render() {
return (
<div>
{this.props.message} {this.state.count}
</div>
);
}
}

在 TypeScript Playground 中查看

不要忘记您可以导出/导入/扩展这些类型/接口以重复使用。

为什么两次注释 state

严格来说,没有必要注释 state 类属性,但它允许在访问 this.state 和初始化状态时获得更好的类型推断。

这是因为它们以两种不同的方式工作,第二个泛型类型参数将允许 this.setState() 正确工作,因为该方法来自基类,但组件内部初始化 state 会覆盖基类实现,因此您必须确保告诉编译器您实际上没有做任何不同的事情。

请参阅 @ferdaber 在此处的评论.

不需要 readonly

您经常会看到示例代码包含 readonly 来标记 props 和 state 为不可变的。

type MyProps = {
readonly message: string;
};
type MyState = {
readonly count: number;
};

这是不需要的,因为 React.Component<P,S> 已经将它们标记为不可变的。(查看 PR 和讨论!

类方法:像往常一样操作,但请记住您函数的任何参数也需要进行类型化。

class App extends React.Component<{ message: string }, { count: number }> {
state = { count: 0 };
render() {
return (
<div onClick={() => this.increment(1)}>
{this.props.message} {this.state.count}
</div>
);
}
increment = (amt: number) => {
// like this
this.setState((state) => ({
count: state.count + amt,
}));
};
}

在 TypeScript Playground 中查看

类属性:如果您需要声明类属性以供以后使用,只需像 state 一样声明它,但无需赋值。

class App extends React.Component<{
message: string;
}> {
pointer: number; // like this
componentDidMount() {
this.pointer = 3;
}
render() {
return (
<div>
{this.props.message} and {this.pointer}
</div>
);
}
}

在 TypeScript Playground 中查看

有需要补充的内容?提交问题.

类型化 getDerivedStateFromProps

在开始使用 getDerivedStateFromProps 之前,请先阅读 文档您可能不需要派生状态。派生状态可以使用 hooks 实现,这也有助于设置记忆化。

以下是一些您可以注释 getDerivedStateFromProps 的方法。

  1. 如果您已明确类型化派生状态并希望确保 getDerivedStateFromProps 的返回值符合它。
class Comp extends React.Component<Props, State> {
static getDerivedStateFromProps(
props: Props,
state: State
): Partial<State> | null {
//
}
}
  1. 当您希望函数的返回值确定您的状态时。
class Comp extends React.Component<
Props,
ReturnType<typeof Comp["getDerivedStateFromProps"]>
> {
static getDerivedStateFromProps(props: Props) {}
}
  1. 当您希望使用其他状态字段和记忆化的派生状态时。
type CustomValue = any;
interface Props {
propA: CustomValue;
}
interface DefinedState {
otherStateField: string;
}
type State = DefinedState & ReturnType<typeof transformPropsToState>;
function transformPropsToState(props: Props) {
return {
savedPropA: props.propA, // save for memoization
derivedState: props.propA,
};
}
class Comp extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
otherStateField: "123",
...transformPropsToState(props),
};
}
static getDerivedStateFromProps(props: Props, state: State) {
if (isEqual(props.propA, state.savedPropA)) return null;
return transformPropsToState(props);
}
}

在 TypeScript Playground 中查看