[英]How to access values from the constructor in an array of objects
我有一個反應組件maintoolbar.tsx
,它有一個網格對象作為道具傳遞給它
import React from 'react';
import { Grid } from '../grid';
interface PropsInterface {
grid: Grid;
}
const MainToolbar: React.FC<PropsInterface> = (props: PropsInterface) => {
const { grid } = props;
const test = grid.mainToolbar.shapes[0].name;
// ^ doesnt return the name
const newNode = () => {
grid.newNode();
};
return (
<div className='main-toolbar'>
...
</div>
);
};
export { MainToolbar };
這就是我得到的返回值,但是如何訪問 this.name 的值?
class Square {
constructor(nodes) {
this.name = 'square';
我從道具中得到的網格對象有一個對象數組
import { Square } from './components/square';
class Grid {
constructor() {
this.mainToolbar = {
shapes: [Square],
};
}
}
export { Grid };
最后是正方形
class Square {
name: string;
constructor(nodes: NodesInterface) {
this.name = 'square';
}
}
export { Square };
如果做console.log(grid.mainToolbar.shapes);
我得到了我以前從未見過的 [f] 東西
如果我做console.log(grid.mainToolbar.shapes[0], ' type ' , typeof grid.mainToolbar.shapes[0]);
我明白了
更新
添加
interface MainToolbarInterface {
[key: string]: any;
}
class Grid
mainToolbar: MainToolbarInterface;
constructor() {
this.mainToolbar = {
shapes: [new Square(this)],
};
}
給我名字,顯然任何都不對,應該是什么?
在您的Grid
構造函數中。 你有
constructor() {
this.mainToolbar = {
shapes: [Square],
};
}
這使得shapes
= 一個以Square
類為第一個元素的數組。
嘗試
constructor() {
this.mainToolbar = {
shapes: [new Square()],
};
}
如果你不想在那里初始化它,這就是類型定義。 然后改為
constructor() {
this.mainToolbar = {
shapes: [],
}: {
shape: Square[]
};
}
更新后。 對於接口類型。
interface MainToolbarInterface {
shapes: Array<Square>;
}
class Grid
mainToolbar: MainToolbarInterface;
constructor() {
this.mainToolbar = {
shapes: [new Square(this)],
};
}
或shapes: Square[];
若你寧可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.