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

这是我的包.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"
  }
}

我在这里做错什么了?

最佳答案

应该是:

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

不同之处在于onClick值不应该被引号包围。
引号使其成为字符串,而不是对方法的引用。

10-06 13:00