你好,我对 React 相当陌生,但我选择使用 typescript(我也是新手)而不是原始 JS。话虽如此,我在向react-map-gl 元素添加图层时遇到了麻烦。 这是我收到的错误代码
Type '{ id: string; type: string; paint: { 'sky-type': string; 'sky-atmosphere-sun': number[]; 'sky-atmosphere-sun-intensity': number; }; }' is not assignable to type 'LayerProps'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"symbol" | "sky" | "circle" | "line" | "fill" | "fill-extrusion" | "raster" | "background" | "heatmap" | "hillshade"'.ts(2322)
看起来像是它说需要一个枚举? 以下是代码片段:
const skyLayer = {
id: 'sky',
type: 'sky',
paint: {
'sky-type': 'atmosphere',
'sky-atmosphere-sun': [0.0, 0.0],
'sky-atmosphere-sun-intensity': 15
}
};
这个是给我红色波浪线的(在图层下):
<Layer {...skyLayer} />
以及我试图遵循的示例代码: https://github.com/visgl/react-map-gl/blob/6.1-release/examples/terrain/src/app.js
EDIT1:我按照代码中的建议更改了内容,但我似乎无法解决问题。这是我收到的错误:
Type '{ id: string; type: "sky"; paint: { "sky-type": string; "sky-atmosphere-sun": number[]; "sky-atmosphere-sun-intensity": number; }; }' is not assignable to type 'LayerProps'.
Types of property 'paint' are incompatible.
Type '{ "sky-type": string; "sky-atmosphere-sun": number[]; "sky-atmosphere-sun-intensity": number; }' is not assignable to type 'BackgroundPaint | FillPaint | FillExtrusionPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint | HeatmapPaint | HillshadePaint'.
Type '{ "sky-type": string; "sky-atmosphere-sun": number[]; "sky-atmosphere-sun-intensity": number; }' has no properties in common with type 'HillshadePaint'.ts(2322)
在声明
type
时,您应该为 skyLayer
声明数据类型。因为默认的 type
将是字符串并且可以传递到 Layer
中。您可以使用 as
来做到这一点:
const skyLayer = {
id: 'sky',
type: 'sky' as 'sky',
paint: {
'sky-type': 'atmosphere',
'sky-atmosphere-sun': [0.0, 0.0],
'sky-atmosphere-sun-intensity': 15
}
};
您应该从react-map-gl 导入
SkyLayer
作为类型。
import type {SkyLayer} from 'react-map-gl';
const skyLayer:SkyLayer = {
id: 'sky',
type: 'sky',
paint: {
'sky-type': 'atmosphere',
'sky-atmosphere-sun': [0.0, 0.0],
'sky-atmosphere-sun-intensity': 15
}
};
看看这个示例。