typescript React js Typescript字符串数组变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/45498178/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React js Typescript string array variable
提问by mo_maat
I have the following two components. I think I'm having trouble properly declaring my array object to match the interface I've declared. Why do I get the following error on all my properties?
我有以下两个组件。我想我无法正确声明我的数组对象以匹配我声明的接口。为什么我的所有属性都会出现以下错误?
[0] (10,5): error TS2304: Cannot find name 'color'.
[0] (11,5): error TS2304: Cannot find name 'id'.
[0] (10,5): 错误 TS2304: 找不到名称“颜色”。
[0] (11,5):错误 TS2304:找不到名称“id”。
app.tsx
应用程序.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"));
Car Component
汽车零部件
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>;
    }
}
回答by hendrixchord
It's because you've declared you props type as string[]
这是因为你已经将 props 类型声明为 string[]
Declare the interface for your object
声明对象的接口
interface Car
{
    id: number, 
    make: string,
    year: number,
    color: string,
}
And then declare you props as
然后将你的道具声明为
interface CarProps {
    cars: Car[];
}

