【发布时间】:2016-01-20 06:30:05
【问题描述】:
我已经弄清楚如何使用丑陋的事件强制转换来将事件处理程序绑定到 SELECT 元素上。
是否可以在不强制转换的情况下以类型安全的方式检索值?
import React = require('react');
interface ITestState {
selectedValue: string;
}
export class Test extends React.Component<{}, ITestState> {
constructor() {
super();
this.state = { selectedValue: "A" };
}
change(event: React.FormEvent) {
console.log("Test.change");
console.log(event.target); // in chrome => <select class="form-control" id="searchType" data-reactid=".0.0.0.0.3.1">...</select>
// Use cast to any works but is not type safe
var unsafeSearchTypeValue = ((event.target) as any).value;
console.log(unsafeSearchTypeValue); // in chrome => B
this.setState({
selectedValue: unsafeSearchTypeValue
});
}
render() {
return (
<div>
<label htmlFor="searchType">Safe</label>
<select className="form-control" id="searchType" onChange={ e => this.change(e) } value={ this.state.selectedValue }>
<option value="A">A</option>
<option value="B">B</option>
</select>
<h1>{this.state.selectedValue}</h1>
</div>
);
}
}
【问题讨论】:
-
类型安全是什么意思?
-
我猜这意味着由打字稿编译并检查所有变量的赋值是否符合它们的类型。我们说的是打字稿,当然不是 javascript
标签: javascript reactjs typescript