reactjs.org官方网站包含了一个优秀的入门教程.

教程片段是用JavaScript编写的,我正在try 将它们转换为TypeScript.

我已经设法让代码正常工作,但对使用接口有疑问.

onClick回调的正确"函数签名"应该是什么.

Is there a way to replace the 'any' keyword in the IProps_Square interface with an explicit function signature ?

任何帮助或建议都将不胜感激,非常感谢Russell

index.html

<!DOCTYPE html>
<html lang="en">
<body>
<div id="reactjs-tutorial"></div>
</body>
</html> 

index.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')   
); 

推荐答案

有props 的interface人应该是

interface IProps_Square {
  message: string;
  onClick: React.MouseEventHandler<HTMLButtonElement>;
}

还要注意,如果使用分号,接口项分隔符是分号,而不是逗号.

Typescript相关问答推荐

如何传递基于TypScript中可变类型的类型?

TS 2339:属性切片不存在于类型DeliverableSignal产品[]上>'

替代语法/逻辑以避免TS变量被分配之前使用." "

接口的额外属性作为同一接口的方法的参数类型'

如果请求是流,如何等待所有响应块(Axios)

在TypeScrip的数组中判断模式类型

返回具有递归属性的泛型类型的泛型函数

如何解决类型T不能用于索引类型{ A:typeof A; B:typeof B;. }'

为什么我的条件类型不能像我预期的那样工作?

在排版修饰器中推断方法响应类型

基于泛型的条件接口键

回调函数中的TypeScrip类型保护返回Incorect类型保护(具有其他未定义类型的返回保护类型)

作为函数参数的联合类型的键

如何在Reaction 18、Reaction-Rout6中的导航栏中获取路由参数

如何从上传文件中删除预览文件图标?

扩展对象的此内容(&Q;)

为什么受歧视的unions 在一种情况下运作良好,但在另一种非常类似的情况下却不起作用?

在Vite中将SVG导入为ReactComponent-不明确的间接导出:ReactComponent

在ts中获取级联子K类型?

带有过滤键的 Typescript 映射类型