Programing

반응의 onClick 이벤트에 대한 TypeScript 인터페이스 서명JS

c10106 2022. 3. 24. 21:14
반응형

반응의 onClick 이벤트에 대한 TypeScript 인터페이스 서명JS

reactjs.org의 공식 웹사이트는 훌륭한 소개 자습서를 포함하고 있다.

자습서 스니펫은 자바스크립트로 작성되어 있으며, 나는 이것을 TypeScript로 변환하려고 한다.

나는 간신히 코드를 작동시켰지만 인터페이스 사용에 대해 질문이 있다.

onClick 콜백에 올바른 "기능 서명"을 선택하십시오.

IProps_Square 인터페이스의 '임의' 키워드를 명시적 함수 서명으로 대체할 방법이 있는가?

어떤 도움이나 제안이라도 정말 고마워, 러셀.

인덱스.포인트

<!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 인터페이스의 '임의' 키워드를 명시적 함수 서명으로 대체할 방법이 있는가?

난 그냥.() => 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')   
); 

그러나 매개 변수가 필요한 경우 매개 변수의 적절한 유형은 다음과 같다.React.MouseEvent<HTMLElement>, 그래서:

interface IProps_Square {
  message: string,
  onClick: (e: React.MouseEvent<HTMLElement>) => void,
}

참조URL: https://stackoverflow.com/questions/54433183/typescript-interface-signature-for-the-onclick-event-in-reactjs

반응형