programing

속성 'XYZ'가 유형 '읽기 전용<{ children?:'에 없습니다.React Node; }> & 읽기 전용 <{}>

jooyons 2023. 3. 26. 11:12
반응형

속성 'XYZ'가 유형 '읽기 전용<{ children?:'에 없습니다.React Node; }> & 읽기 전용 <{}>

RecipeList.js와 Recipe.js의 .prop에 액세스하려고 하면 구문 오류가 발생합니다.

여기 Recipe 코드 샘플이 있습니다.js:

import React, {Component} from 'react';
import "./Recipe.css";

class Recipe extends Component {

    // props: any; uncommenting this will fix the bug

    render() {
        // don't have to use return and parentheses for arrow with JSX
        const ingredients = this.props.ingredients.map((ing, ind) => (
            <li key={ind}>{ing}</li>
        ));
        const {title, img, instructions} = this.props

        return (
            <div className="recipe-card">
                <div className="recipe-card-img">
                    <img src={img} alt={title}/>
                </div>
                <div className="recipe-card-content">
                    <h3 className="recipe-title">
                        {title}
                    </h3>
                    <h4>
                        Ingredients:
                    </h4>
                    <ul>
                        {ingredients}
                    </ul>
                    <h4>
                        Instructions:
                    </h4>
                    <p>
                        {instructions}
                    </p>
                </div>
            </div>
        )
    }
}

.props의 스크린샷 오류

그러나 이 프로젝트는 컴파일 시간 오류를 발생시키지 않으며 웹 사이트는 완벽하게 작동합니다.

Chrome 콘솔 또는 터미널 오류 없이 정상적으로 작동하는 스크린샷

리액트 튜토리얼 프로젝트를 에디터에 작성했을 때(최종 인덱스를 복사해 넣기까지 했다) 비슷한 문제가 발생하기 때문에 코드와 관련이 적고, VS코드용 Javascript 또는 사전 설정 구성 중 하나에서 컴포넌트별로 .props 속성을 식별하는 데 문제가 있다고 생각합니다.만약을 위해 사이트에서 js 코드를 입력해 주세요.) 앱이 컴파일 시간 오류 없이 정상적으로 동작하고 있습니다.

리액트 튜토리얼에 따라 동일한 .prop 오류의 스크린샷

이 문제를 해결하는 유일한 방법은 실제로 하드코드를 사용하여 각 클래스의 소품 속성을 만들고 다음과 같이 설정하는 것입니다.

구문 오류 해결 방법만 스크린샷

갱신된 의존관계는 다음과 같습니다.

"dependencies": {
  "@types/react": "^16.4.13",
  "prop-types": "^15.6.2",
  "react": "^16.5.0",
  "react-dom": "^16.5.0",
  "react-scripts": "1.1.5",
  "typescript": "^3.0.3"
 }

인터페이스와 TypeScript의 일반적인 React 구현을 사용하여 소품과 상태를 정의해야 합니다.요소

import React, {Component} from 'react';
import "./Recipe.css";

interface IRecipeProps {
  ingredients?: string[];
  title?: string;
  img?: string;
  instructions?: string;
}

interface IRecipeState {
}

class Recipe extends Component<IRecipeProps, IRecipeState> {
    render() {
        const ingredients = this.props.ingredients.map((ing, ind) => (
            <li key={ind}>{ing}</li>
        ));
        const {title, img, instructions} = this.props

        return (
            <div className="recipe-card">
                Your render code here
            </div>
        )
    }
}
  • 파일 확장자를 다음과 같이 변경합니다..tsxTypeScript를 사용하여 React 파일임을 나타냅니다.->Recipe.tsx
  • 데이터에 맞게 유형(스트링)을 조정하십시오.
  • 사용하다IRecipeState컴포넌트 상태의 구조를 정의합니다(this.state.fooBar)는, 상태를 사용하지 않기 때문에, 현시점에서는 비워 두는 것이 좋습니다.
  • 에러를 발생시키는 다른 컴포넌트에 대해서도, 같은 조작을 실시해 주세요).RecipeList.js)

이 문제를 해결할 수도 있습니다.

class Recipe extends React.Component<any, any>{

....
....

// The rest of your normal code
}

Klugjos의 대답에 근거합니다.React의 기능 컴포넌트(FC)에서도 같은 작업을 수행할 수 있으며 useState Hook을 사용하여 상태를 관리할 수 있습니다.

import React, {FC} from 'react';
import "./Recipe.css";

interface IRecipeProps {
  ingredients?: string[];
  title?: string;
  img?: string;
  instructions?: string;
}

interface IRecipeState {
}

const Recipe:FC<IRecipeProps> = (props) => {

    const { ingredients, title, img, instructions} = props;

    ingredients.map(( ingredient, index) => (
        <li key={index}>
          { ingredient}
        </li>
    ));

    return (
        <div className="recipe-card">
            Your render code here
        </div>
    )
}

언급URL : https://stackoverflow.com/questions/52249390/property-xyz-does-not-exist-on-type-readonly-children-reactnode-rea

반응형