相关疑难解决方法(0)

打字稿输入onchange event.target.value

在我的react和typescript应用程序中,我使用:onChange={(e) => data.motto = (e.target as any).value}.

我如何正确定义类的类型,所以我不必破解我的类型系统any

export interface InputProps extends React.HTMLProps<Input> {
...

}

export class Input extends React.Component<InputProps, {}> {
}
Run Code Online (Sandbox Code Playgroud)

如果我把target: { value: string };我得到:

ERROR in [default] /react-onsenui.d.ts:87:18
Interface 'InputProps' incorrectly extends interface 'HTMLProps<Input>'.
  Types of property 'target' are incompatible.
    Type '{ value: string; }' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)

types typescript reactjs typescript-typings

84
推荐指数
14
解决办法
9万
查看次数

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万
查看次数