小编dav*_*ens的帖子

typesafe使用reactjs和typescript选择onChange事件

我已经想出如何使用事件的丑陋演员来绑定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" …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs

53
推荐指数
7
解决办法
7万
查看次数

标签 统计

javascript ×1

reactjs ×1

typescript ×1