Programing

임의/일반 소품이 있는 구성 요소를 TypeScript에서 reaction-remensx 연결 기능으로 전달

c10106 2022. 3. 20. 12:28
반응형

임의/일반 소품이 있는 구성 요소를 TypeScript에서 reaction-remensx 연결 기능으로 전달

반응 요소를 연결하려고 하는 경우react-redux임의의 소품들을 가지고 있지만, 제대로 컴파일되지 않고 있다.나는 사용해 보았다.JSXElementConstructor그리고(new (props: Props) => React.Component<Props, any>)대신에ComponentType, 그러나 방법에 대한 다른 오류를 얻었다.Props다른 유형으로 인스턴스화할 수 있다.여기 암호가 있다.어떤 도움이라도 감사할 것이다.

https://github.com/piotrwitek/react-redux-typescript-guide/issues/55은 관련 있어 보이지만, 그것은 소품 자체가 일반 소품이 아닌 일반 소품을 갖는 것에 관한 것으로 보인다.

코드

import React from "react";
import { connect } from "react-redux";

interface StoreState {
  someState: number;
}

// Tried `React.JSXElementConstructor<Pros>`
// and `(new (props: Props) => React.Component<Props, any>)`
// instead of `React.ComponentType<Props>`, but got a different error.
function createWrapperComponent<Props>(
  componentElement: React.ReactElement<
    Props,
    React.ComponentType<Props> & { update(props: Props): void }
  >
) {
  const props = componentElement.props;
  const UnconnectedComponent = componentElement.type;
  const ConnectedComponent = connect<StoreState, {}, Props, StoreState>(
    (state) => state
  )(UnconnectedComponent);

  return class WrapperComponent extends React.Component<any> {
    static update = UnconnectedComponent.update;
    render() {
      return <ConnectedComponent {...props} />;
    }
  };
}

플레이그라운드 링크: 제공됨

업데이트: 초기 캐스팅을 방지하는 접근 방식any이제 나는 전달된 소품들을 캐스팅하고 있다.ConnectedComponent대신에그곳의 유형 문제를 조사하면 내가 언급했던 것보다 더 많은 잠재적 문제가 있는지 알 수 있을 것이다.


네가 하는 짓은 말이 안 된다.만약Props이었다{ someState: string }당신의UnconnectedComponent그것을 기대하고 있을 것이다.someState…이 되도록 떠받치다.string, 그러나 그것은.number.

만약stateProps그리고dispatchProps무효화해야 한다ownProps당신의 코드가 지금 어떤 역할을 하고 있는지, 나는 당신이 원하는 방식으로 타입을 자동으로 작동시킬 수 있을지 확신할 수 없다.TypeScript는 다음과 같은 것이 소리라는 것을 알아낼 수 없다.

function a<Props>(
  b: { [K in keyof Props]: K extends keyof StoreState ? StoreState[K] : Props[K] }
): Omit<Props, keyof StoreState>
{
  return b;
}

총알을 물어뜯어서 써야 할지도 몰라.any여기 전화 걸기 유형을 안전하게 만드는 방법의 샘플이 있다.

대신 원한다면ownProps무효로 하다stateProps, 당신은 제공하기를 원할 것이다.mergeProps에 대해 논하다.connect.

단, a를 생성할 때는 주의하십시오.ReactElementJSX를 통해type필드에 유형이 있음any물론, 만약 당신이 전화한다면, 타입의 안전은 주지 않을 것이다.createComponent.

당신..Props어떤 유형도 정의되어 있지 않다.그럼 그냥 비워두면 되는 건가?

function createComponent(componentElement: React.ReactElement<{}, React.ComponentType>) {
  const props = componentElement.props;
  const UnconnectedComponent = componentElement.type;
  const ConnectedComponent = connect<StoreState, {}, {}, StoreState>(state => state)(UnconnectedComponent);

  return <ConnectedComponent {...props} />
}

참조URL: https://stackoverflow.com/questions/61838048/pass-component-with-arbirtrary-generic-props-to-react-redux-connect-function-in

반응형