簡體   English   中英

錯誤TS2345:類型為'{x:number; y:數字; z:數字; }'不可分配給'string'類型的參數

[英]error TS2345: Argument of type '{ x: number; y: number; z: number; }' is not assignable to parameter of type 'string'

我正在嘗試使用接收到的值動態創建一個圖像。 但是以某種方式我在設置imgObj的position屬性時出現下面的錯誤(下面的代碼)

xpos, yposzpos包含字符串浮動值,例如xpos = "-0.2", ypos="-0.1", zpos="0.2"

var imgObj = document.createElement("a-image");
imgObj.setAttribute("src",'url(' + $event.src + ')');
//imgObj.setAttribute("position",{x:0,y:0,z:0})
imgObj.setAttribute('position',{x:xpos, y:ypos, z:zpos});

任何想法或建議都會有所幫助...謝謝

如果您沒有使用Aframe,那將是TypeScript的正確行為,因為在僅DOM / HTML的世界中,將對象作為setAttribute的值會得到意外的結果。

要告知TypeScript aframe所增加的額外功能,您可以安裝aframe類型:

npm install -D @types/aframe

當屬性為時,這將添加如下類型: setAttribute可以接受帶有x,y,z數字的對象。

從鍵入內容引用https://unpkg.com/@types/aframe@0.8.0/index.d.ts

export interface Coordinate {
    x: number;
    y: number;
    z: number;
}

然后在文件中降低:

setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;

因此,看起來應該這樣做。

最后的想法

值得注意的是,aframe不建議為此使用setAttribute ,如其文檔中所示: https ://aframe.io/docs/0.8.0/components/position.html

為了提高性能和人機工程學,我們建議直接通過three.js Object3D .position Vector3與.setAttribute來更新位置。

此方法更容易,因為我們可以訪問所有Vector3實用程序,並且通過跳過.setAttribute開銷並且不需要創建對象來設置旋轉即可更快地實現:

我想解決方案是不使用Typescript。 它不希望DOM方法被覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM