gpt4 book ai didi

reactjs - 抽象 React 组件状态中的 TypeScript 交集类型导致只读错误

转载 作者:行者123 更新时间:2023-12-05 07:38:54 24 4
gpt4 key购买 nike

我一直在尝试在不破坏 TypeScript 类型系统规则的情况下,在 React 中创建一个抽象组件。根据 React 的类型,如果在组件的构造函数中设置状态,则它必须是完整的(已分配所有必需的属性)。一种选择是让子类设置整个状态,包括其父类定义的值。为了避免可能导致的重复,我试图让子类可以将此信息传递给抽象类。这会导致一个对我来说意义不大的只读错误。这是我正在使用的代码:

import * as React from 'react';

function intersect<T1 extends Object, T2 extends Object>(o1: T1, o2: T2): T1 & T2 {
let merged: any = {};
// Do anything to merge objects.
return merged;
}

interface AbstractState {
example: boolean;
}

abstract class IntersectionStateComponent<S> extends React.Component<undefined, AbstractState & S> {
constructor(props: undefined, childState: S) {
super(props);
let baseState: AbstractState = {
example: true
};
this.state = intersect(baseState, childState);
}

render() {
return <div></div>
}
}

abstract class NonIntersectComponent extends React.Component<undefined, AbstractState> {
constructor(props: undefined) {
super(props);
let state: AbstractState = {
example: true
}
this.state = state;
}

render() {
return <div></div>;
}
}

NonIntersectComponent的构造函数,当设置状态时,不会发生错误。正在分配 AbstractStateReadonly<AbstractState>被认为是有效的。另一方面,IntersectionStateComponent不会编译,声称:

IntersectionProblem.tsx(19,9): error TS2322: Type 'AbstractState & S' is not assignable to type 'Readonly<AbstractState & S>'.

这里的交集类型有什么区别?

最佳答案

这样就可以了:

this.state = intersect(baseState, childState) as Readonly<AbstractState & S>;

请记住,您正在做的是一种反模式。 React 建议使用组合而不是继承。

"At Facebook, we use React in thousands of components, and we haven’t found any use cases where we would recommend creating component inheritance hierarchies."

更多信息:https://reactjs.org/docs/composition-vs-inheritance.html

关于reactjs - 抽象 React 组件状态中的 TypeScript 交集类型导致只读错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47459761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com