[英]TypeScript interface signature for the onClick event in ReactJS
官方reactjs.org網站包含一個優秀的介紹性教程。
教程片段是用 JavaScript 編寫的,我正在嘗試將它們轉換為 TypeScript。
我設法使代碼正常工作,但對使用接口有疑問。
onClick 回調的正確“函數簽名”應該是什么。
有沒有辦法用顯式函數簽名替換 IProps_Square 接口中的“any”關鍵字?
任何幫助或建議將不勝感激,非常感謝羅素
索引.html
<!DOCTYPE html>
<html lang="en">
<body>
<div id="reactjs-tutorial"></div>
</body>
</html>
索引.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IProps_Square {
message: string,
onClick: any,
}
class Square extends React.Component < IProps_Square > {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.message}
</button>
);
}
}
class Game extends React.Component {
render() {
return (
<Square
message = { 'click this' }
onClick = { () => alert('hello') }
/>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('reactjs-tutorial')
);
帶有道具的界面應該是
interface IProps_Square {
message: string;
onClick: React.MouseEventHandler<HTMLButtonElement>;
}
另請注意,如果您使用分號,則界面項分隔符是分號,而不是逗號。
有沒有辦法用顯式函數簽名替換 IProps_Square 接口中的“any”關鍵字
我只是() => void
即一個不帶參數的函數,你不在乎它是否返回任何東西。
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IProps_Square {
message: string,
onClick: () => void,
}
class Square extends React.Component < IProps_Square > {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.message}
</button>
);
}
}
class Game extends React.Component {
render() {
return (
<Square
message = { 'click this' }
onClick = { () => alert('hello') }
/>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('reactjs-tutorial')
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.