我在使用TypeScript编写的React组件中更新状态有问题(与Addons 0.13.3,Typescript 1.6.0-dev.20150804,http://definitelytyped.org/中的定义文件相反).
/// <reference path="react/react-addons.d.ts" /> import React = require("react/addons"); interface AppState { } interface TestState { liked: boolean,name: string } class Tester extends React.Component<any,TestState> { constructor(props) { super(props); this.state = { liked: false,name: "Anders" }; } handleClick(evt,domNode): void { this.setState({ liked: !this.state.liked,name: this.state.name }); } handleChange(evt,a,b,c): void { this.setState({ liked: this.state.liked,name: evt.target.value }); } render() { var text = this.state.liked ? "liked " : "haven't liked " return (<div>You {text} {this.state.name} <button onClick={this.handleClick}>Like</button> <input value={this.state.name} onChange={this.handleChange} /> </div>); } } class App extends React.Component<{},AppState> { constructor(props) { super(props); } render() { return (<div> <Tester /> </div>); } } function Factory(props: {}) { return React.createElement(App,props); } export = Factory;
通话代码是
/// <reference path="react/react-addons.d.ts" /> import React = require("react/addons"); import App = require("app"); React.render(App({}),document.getElementById("jsapp"));
组件按照我的期望呈现,但是handleClick和handleChange方法不会正确更新状态.如果我在这两个方法中设置断点,然后渲染,我将看到以下值:
> render:这是一个Tester对象(我期待什么).
> handleChange:这是一个ReactClass.createClass.Constructor.
> handleClick:这是Window对象的引用.
后两者意味着状态对象不可用.
有意见的建议.