programing

타입스크립트 + 리액트 / 리덕스:타입 'IntrinsicAttributes & IntrinsicClassAttributes'에 속성 'XXX'가 존재하지 않습니다.

oldcodes 2023. 3. 20. 23:35
반응형

타입스크립트 + 리액트 / 리덕스:타입 'IntrinsicAttributes & IntrinsicClassAttributes'에 속성 'XXX'가 존재하지 않습니다.

Typescript, React 및 Redux(모두 Electron으로 실행)를 사용하는 프로젝트를 진행하고 있는데, 클래스 기반 컴포넌트를 다른 컴포넌트에 포함시키고 이들 컴포넌트 간에 파라미터를 전달하려고 할 때 문제가 발생했습니다.대략적으로 말하면, 컨테이너 구성요소의 구조는 다음과 같습니다.

class ContainerComponent extends React.Component<any,any> {
  ..
  render() {
    const { propToPass } = this.props;
    ...
    <ChildComponent propToPass={propToPass} />
    ...
  }
}

....
export default connect(mapStateToProps, mapDispatchToProps)(ContainerComponent);

그리고 하위 구성 요소:

interface IChildComponentProps extends React.Props<any> {
  propToPass: any
}

class ChildComponent extends React.Component<IChildComponentProps, any> {
  ...
}

....
export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent);

물론 기본만 포함하고 있고 이 두 클래스에는 더 많은 것이 있지만 유효한 코드처럼 보이는 것을 실행하려고 하면 여전히 오류가 발생합니다.발생한 정확한 오류:

TS2339: Property 'propToPass' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ childr...'.

처음 에러를 만났을 때는, 소품을 정의하는 인터페이스를 통과하지 않았기 때문이라고 생각했습니다만, (위에서 보듯이) 작성했는데, 아직 동작하지 않습니다.제가 뭘 놓치고 있는 걸까요?

Container Component의 코드에서 Child Component 프로펠을 제외하면 Child Component에는 중요한 프로펠이 없지만 JSX Typescript에서는 컴파일을 거부합니다.이 기사를 바탕으로 한 연결 래핑과 관련이 있을 수 있다고 생각합니다만, 그 기사의 문제는 index.tsx 파일에서 발생하고 프로바이더에 문제가 있어, 다른 곳에서 문제가 발생하고 있습니다.

그래서 관련된 답변(특히 이것과 이것)을 읽고 질문에 대한 @basarat의 답변을 본 결과, 나에게 맞는 답을 찾을 수 있었습니다.비교적 새로운 리액트에서는 Connect가 컨테이너 컴포넌트에 명시적인 인터페이스를 제공하지 않았기 때문에 통과하려고 하는 소품 때문에 혼란스러웠던 것 같습니다.

따라서 컨테이너 구성요소는 그대로 유지되지만 하위 구성요소는 약간 변경되었습니다.

interface IChildComponentProps extends React.Props<any> {
  ... (other props needed by component)
}

interface PassedProps extends React.Props<any> {
  propToPass: any
}

class ChildComponent extends React.Component<IChildComponentProps & PassedProps, any> {
  ...
}

....
export default connect<{}, {}, PassedProps>(mapStateToProps, mapDispatchToProps)    (ChildComponent);

위는 어떻게든 나에게 통했다.컴포넌트가 컨테이너에서 기대하는 소품을 명시적으로 전달하면 효과가 있는 것처럼 보였고 두 컴포넌트는 모두 올바르게 렌더링되었습니다.

메모: 매우 간단한 답변이라는 것을 알고 있으며, 왜 이것이 효과가 있는지 정확히 알 수 없기 때문에 경험이 많은 리액트 닌자가 이 답변에 대한 지식을 흘리고 싶다면 기꺼이 수정하겠습니다.

저는 단순히 아이 컴포넌트 타입을 React에서 변경했을 뿐입니다.FC에서 JSX로요소

이전(경고)

const Component: React.FC = () => {

After (경고 없음)

const Component = (): JSX.Element => {

새로 추가된 개체 유형을 다시 확인합니다.개체 유형이 예상과 완전히 다르면 이러한 오류가 발생합니다.

예. 컴포넌트에 기재된 소품 유형은 해당 컴포넌트에 전달되는 소품 유형과 일치해야 합니다.

내 경우, 나는 javascript에 있는 컴포넌트를 Import하는 타이프스크립트 컴포넌트를 만들고 있었다.connect.

여기 오류를 바로잡을 수 있는 빠른 방법이 있습니다.

// User is a javascript component
import _User from "./User";

// Inject types that this component accepts
const User = _User as unknown as React.JSXElementConstructor<{
 userId: string
}>;

const UserProfile = () => {
  const user = useCurrentUser();
  return (
    <div className="flex items-center justify-center">
      <User userId={user.userId} />
    </div>
  );
}

도움이 되시길 바랍니다!

하위 구성 요소가 React를 확장하도록 합니다.원하는 유형 또는 "임의" 유형의 구성 요소.예: "extends React.Component<any> {...}"

export class ChildComponent extends React.Component<T> {
 render() {
  return (
    <button className="square">
      {this.props.value}
    </button>
  );
 }
}

그런 다음 상위 구성 요소에서 다음과 같은 값을 전달할 수 있습니다.

renderSquare(i: Number) { return <ChildComponent value={i}/>; }

자세한 내용은 https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/class_components/참조하십시오.

대신export default connect(mapStateToProps, mapDispatchToProps)(ChildComponent);, 를 선호합니다.connect데코레이터 https://github.com/alm-tools/alm/blob/00f2f94efd3810af8a80a49f968c2ebdeb955399/src/app/fileTree.tsx#L136-L146

@connect((state: StoreState): Props => {
    return {
        filePaths: state.filePaths,
        filePathsCompleted: state.filePathsCompleted,
        rootDir: state.rootDir,
        activeProjectFilePathTruthTable: state.activeProjectFilePathTruthTable,
        fileTreeShown: state.fileTreeShown,
    };
})

여기서 connect는 https://github.com/alm-tools/alm/blob/00f2f94efd3810af8a80a49f968c2ebdeb955399/src/typings/react-redux/react-redux.d.ts#L6-L36에서 정의됩니다.

왜요?

사용하고 있는 정의가 최신이 아니거나 유효하지 않은 것 같습니다(작성이 불충분할 수 있습니다).

언급URL : https://stackoverflow.com/questions/42657792/typescript-react-redux-property-xxx-does-not-exist-on-type-intrinsicattrib

반응형