简体   繁体   English

ReactJS 中 onClick 事件的 TypeScript 接口签名

[英]TypeScript interface signature for the onClick event in ReactJS

The official reactjs.org website contains an excellent introductory tutorial.官方reactjs.org网站包含一个优秀的介绍性教程。

The tutorial snippets are written in JavaScript and I am trying to convert these to TypeScript.教程片段是用 JavaScript 编写的,我正在尝试将它们转换为 TypeScript。

I have managed to get the code working but have a question about using interfaces.我设法使代码正常工作,但对使用接口有疑问。

What should the correct "function signature" be for the onClick callback. onClick 回调的正确“函数签名”应该是什么。

Is there a way to replace the 'any' keyword in the IProps_Square interface with an explicit function signature ?有没有办法用显式函数签名替换 IProps_Square 接口中的“any”关键字?

Any help or suggestions would be really appreciated, many thanks Russell任何帮助或建议将不胜感激,非常感谢罗素

index.html索引.html

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

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

The interface with props should be带有道具的界面应该是

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

Notice also that if you use semicolons, the interface items separator is a semicolon, not a comma.另请注意,如果您使用分号,则界面项分隔符是分号,而不是逗号。

Is there a way to replace the 'any' keyword in the IProps_Square interface with an explicit function signature有没有办法用显式函数签名替换 IProps_Square 接口中的“any”关键字

I would just () => void ie a function that takes no arguments and you don't care if it returns anything.我只是() => 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM