我试图通过keys
作为React prop:
import * as React from "react";
import { render } from "react-dom";
const keys: string[] = ["a", "b"];
function App({keys}: string[]) {
return (
<div>
{keys.map((key: string) => (
<li>{key}</li>
))}
</div>
);
}
const rootElement = document.getElementById("root");
render(<App keys={keys} />, rootElement);
但是,我得到这些错误:
属性'map'不存在类型'()=>IterableIterator"。
类型'string[]'不能赋值给类型'()=>IterableIterator"。
为什么会这样?如何解决?
Live code: https://codesandbox.io/s/changing-props-on-react-root-component-forked-9lj9ye?file=/src/index.tsx:0-341
你输入你的整个道具作为string[]
而不是仅仅keys
。在对象中嵌入keys
prop:
function App({ keys }: { keys: string[]; }) {
// ...
或者使用接口:
interface AppProps {
keys: string[];
}
function App({ keys }: AppProps) {
// ...
或者一个类型:
type AppProps {
keys: string[];
}
function App({ keys }: AppProps) {
// ...
进一步:类型别名和接口的区别