我试图摆脱我的 tslint 错误 Type declaration of 'any' loses type-safety.
,但我正在努力找出什么是正确的类型将事件。
我正在通过琳达“ 构建和部署全堆栈反应应用程序”工作,同时试图将其转换为打字机。
以下是造成这一问题的具体原因:
onClick={(event: any) => {
makeMove(ownMark, event.target.index)
}}
我尝试将事件声明为几种不同的类型,比如 React.MouseEvent<HTMLElement>
,以及 HTMLElement 上的一些其他子类型,但没有成功,因为 target.index 不是我能想到的任何类型的属性。我可以从检查员那里看到目前的目标是 Konva。文本和索引被设置为 0
,但不能肯定这对我有帮助,因为我不能设置类型为 Konva.Text
,这对我来说是有意义的,但这也不工作。
下面是我的完整的 React 功能组件:
export const Squares = ({units, coordinates, gameState, win, gameOver, yourTurn, ownMark, move}: SquaresProps) => {
let squares = coordinates.map( (position: number, index: number) => {
let makeMove = move
let mark = gameState[index] !== 'z' ? gameState[index] : false
let fill = 'black'
// when someone wins you want the square to turn green
if (win && win.includes(index)) {
fill = 'lightGreen'
}
if (gameOver || !yourTurn || mark) {
makeMove = () => console.log('nope!')
}
return (
<Text
key={index}
x={position[0]}
y={position[1]}
fontSize={units}
width={units}
text={mark}
fill={fill}
fontFamily={'Helvetica'}
aligh={'center'}
onClick={(event: any) => {
makeMove(ownMark, event.target.index)
}}
/>
)
})
return (
<Layer>
{squares}
</Layer>
)
}
以下是我的 package.json
依赖项:
"dependencies": {
"konva": "^1.6.3",
"material-ui": "^0.18.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-konva": "^1.1.3",
"react-router": "~3.0.0",
"react-tap-event-plugin": "^2.0.1",
"styled-components": "^2.1.0"
},
我 好好想想的索引是由 Konva 层类添加,但我是相当新的整个反应生态系统,所以仍然试图包裹我的大脑周围的一切。
I was able use declaration merging suggestion by Tyler Sebastion to define the index on the target which silenced tslint. I'm not sure this is the best approach though as it feels a bit fragile to me.
下面是附加的接口代码和更新的 onclick 事件:
interface KonvaTextEventTarget extends EventTarget {
index: number
}
interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
target: KonvaTextEventTarget
}
...
return (
<Text
key={index}
x={position[0]}
y={position[1]}
fontSize={units}
width={units}
text={mark}
fill={fill}
fontFamily={'Helvetica'}
aligh={'center'}
onClick={(event: KonvaMouseEvent) => {
makeMove(ownMark, event.target.index)
}}
/>
)