【问题标题】:Cannot assign a function on onClick property of React with Typescript无法使用 Typescript 在 React 的 onClick 属性上分配函数
【发布时间】:2017-05-02 03:31:25
【问题描述】:

我正在尝试使用 Typescript 从 FB React 教程重写国际象棋游戏。

这是一个漫长的旅程,非常具有挑战性。我得到了这个:

ERROR in ./src/Game.tsx
(79,15): error TS2322: Type '{ className: "square"; onClick: "{this.handleClick}"; }' is not assignable to type 'HTMLProps<HTMLButtonElement>'.
  Types of property 'onClick' are incompatible.
    Type '"{this.handleClick}"' is not assignable to type 'EventHandler<MouseEvent<HTMLButtonElement>>'.

这是我的源代码:

interface SquareProps extends React.Props<{}> {
}
interface SquareState {
    value: string
}
class Square extends React.Component<SquareProps, SquareState> {
  constructor(props: SquareProps) {
    super(props)
    this.state = { value: null }

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(): void {
    this.setState({value: 'X'})
  }

  render() {
    return (
      <button className="square" onClick="{this.handleClick}">
        {this.state.value}
      </button>
    );
  }
}

这是我的 package.json

{
  "name": "typescript-react-webpack",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --module-bind 'css=style!css'",
    "webpack-watch": "webpack --progress --colors --watch --module-bind 'css=style!css'",
    "start": "serve"
  },
  "devDependencies": {
    "serve": "^5.1.4",
    "ts-loader": "^2.0.0",
    "typescript": "^2.1.6",
    "webpack": "^2.2.1"
  },
  "dependencies": {
    "@types/react": "^15.0.23",
    "@types/react-dom": "^15.5.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  }
}

我在这里做错了什么?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    应该是:

    render() {
        return (
            <button className="square" onClick={ this.handleClick }>
                {this.state.value}
            </button>
        );
    }
    

    不同之处在于 onClick 值不应被引号括起来。
    引号使它成为一个字符串,而不是对方法的引用。

    【讨论】:

    • 天啊。你刚刚拯救了我的一天。这是一个愚蠢的新手问题。谢谢!
    • 当然可以。我也错过了你在 ctor 中绑定方法,我编辑并删除了我答案的那部分
    猜你喜欢
    • 2023-02-02
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多