无法使用Typescript在React的onClick属性上分配函数

时间:2017-05-02 03:31:26

标签: reactjs typescript

我正在尝试使用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"
  }
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:7)

应该是:

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

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

相关问题