【问题标题】:React js Typescript string array variableReact js Typescript字符串数组变量
【发布时间】:2017-08-04 04:15:03
【问题描述】:

我有以下两个组件。我认为我无法正确声明我的数组对象以匹配我声明的接口。为什么我的所有属性都出现以下错误?

[0] (10,5):错误 TS2304:找不到名称“颜色”。
[0] (11,5): 错误 TS2304: 找不到名称 'id'。

app.tsx

import * as React from "react";
import * as ReactDOM from "react-dom";

const cars = [
    { id: 1, make: "Make1",  year: 2016, color: "black" },
    { id: 2, make: "Make2",  year: 2006, color: "gray" },
    { id: 3, make: "Make3",  year: 2012, color: "purple" },
];

ReactDOM.render(<CarTool cars={cars} />, document.querySelector("main"));

汽车组件

import * as React from "react";    
import * as ReactDOM from "react-dom";

interface CarProps {
    cars: string[];
}    

export class Car extends React.Component<CarProps, void> {
    public render() {
        return <div>
            <h1>Car Tool</h1>
            <table>
                <thead>
                    <tr>
                        <td>Make</td>
                        <td>Year</td>
                        <td>Color</td>
                    </tr>
                </thead>
                <tbody>
                    {this.props.cars.map((car) => <tr><td>car.make</td></tr>)}
                </tbody>
            </table>
        </div>;
    }
}

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    这是因为您已将 props 类型声明为 string[]

    为你的对象声明接口

    interface Car
    {
        id: number, 
        make: string,
        year: number,
        color: string,
    }
    

    然后将你的道具声明为

    interface CarProps {
        cars: Car[];
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2018-12-29
      • 2021-04-28
      • 1970-01-01
      • 2016-07-17
      • 2021-11-30
      • 1970-01-01
      • 2017-09-27
      • 2015-03-08
      相关资源
      最近更新 更多