Property 'XYZ' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

后端 未结 2 2017
再見小時候
再見小時候 2021-01-01 14:28

I get a syntax error when trying to access .props for the both the RecipeList.js and Recipe.js.

Here is a code sample for Recipe.js:

import React, {Com         


        
相关标签:
2条回答
  • 2021-01-01 14:42

    Basing on Klugjos answer. You could do the same with React's functional component (FC) and use the useState Hook to manage the state.

    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>
        )
    }
    
    0 讨论(0)
  • 2021-01-01 14:58

    You need to define what your props and state will look like using an interface and TypeScript's generic implementation of React.Component

    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>
            )
        }
    }
    
    • I would change the file extension to .tsx to indicate that it is a React file using TypeScript -> Recipe.tsx
    • Please adjust the types (strings) to fit your data.
    • Use IRecipeState to define the structure of your Component state (this.state.fooBar). It is ok to leave it empty for now, since you don't make use of the state.
    • Make sure you do the same for your other Component that throws an error (RecipeList.js)
    0 讨论(0)
提交回复
热议问题