typescript React 复选框事件和处理程序的打字稿类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45665188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:48:47  来源:igfitidea点击:

Typescript types for React checkbox events and handlers?

reactjstypescript

提问by Kokodoko

I'm building something like this React examplein Typescript. The goal is to have a parent that has a state, and it creates several stateless child components that pass their clicks back to the parent.

我正在用 Typescript构建类似这个 React 示例的东西。目标是拥有一个具有状态的父组件,它会创建几个无状态的子组件,将它们的点击传递回父组件。

Since the example is in Javascript I have no idea what the types of the input box events and the onChange handlers are...? I've tried several options like React.MouseEvent<HTMLInputElement>, but that's just guesswork...

由于示例是在 Javascript 中,我不知道输入框事件和 onChange 处理程序的类型是什么......?我已经尝试了几个选项,比如React.MouseEvent<HTMLInputElement>,但这只是猜测......

Parent componentcreate imageRows and pass the handler:

父组件创建 imageRows 并传递处理程序:

render() {
  <div>
    <ImageRow key={el.url} onChange={this.onChange}/>
  </div>
 }
 // what should the type of e be?
 onChange(e:any){
 }

And the ImageRow component

和 ImageRow 组件

export interface ImageRowProps { 
  genre: Array<number>
  url: string
  onChange : any // what is the type of the callback function?
}

export class ImageRow extends React.Component<ImageRowProps> {
  render() {
    return <div className="imagerow">
        <input type="checkbox" key={index} onChange={this.props.onChange} defaultChecked={(num == 1)}/>
    </div>
}

EDIT

编辑

The similar question only shows the event type, not the handler type. When I change the event type:

类似的问题只显示事件类型,而不是处理程序类型。当我更改事件类型时:

onChange(e: React.FormEvent<HTMLInputElement>){
    console.log(e.target.value)
}

I get this error:

我收到此错误:

Property 'value' does not exist on type 'EventTarget'.

回答by basarat

When in doubt let it infer it for you by using an arrow in position e.g.

如有疑问,请使用位置箭头为您推断,例如

enter image description here

在此处输入图片说明

Answer

回答

In your case eis React.ChangeEvent<HTMLInputElement>.

在你的情况下eReact.ChangeEvent<HTMLInputElement>.

回答by Thulasiram

In our application,

在我们的应用程序中,

console.log(event.target.value); // Not Working (Blank value)

console.log(event.target.value); // 不工作(空值)

console.log(event.target.checked); // Working Fine ( true / false )

console.log(event.target.checked); // 工作正常(真/假)

//../src/components/testpage2/index.tsx

import * as React from 'react';
import {  TestInput } from '@c2/component-library';

export default class extends React.Component<{}, {}> {
    state = {
                model: {
                    isUserLoggedIn: true
                }            
            };

    onInputCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        console.log(event.target.value); // Not Working
        console.log(event.target.checked); // Working

        const field = event.target.name;
        const model = this.state.model;      
        model[field] = event.target.checked;

        return this.setState({model: model});
    };

    render() {
        return (
            <div>
                <TestInput name="isUserLoggedIn" label="Is User LoggedIn : " type="checkbox" onChange={this.onInputCheckboxChange} />
            </div>
        );
    }
}

//=============================================================//

import * as React from 'react';
//import * as cs from 'classnames';

export interface TestInputProps extends React.HTMLAttributes<HTMLInputElement> {
    name: string;
    label: string;
    onChange: React.ChangeEventHandler<HTMLInputElement>;
    placeholder?: string;
    value?: string;
    type?: string;
    error?: string;
    className?: string;
}

export const TestInput : React.SFC<TestInputProps> = ({ name, label, onChange, placeholder, value, type, className, error, ...rest }) => {
    let wrapperClass:string = 'form-group';
    if (error && error.length > 0) {
      wrapperClass += " " + 'has-error';
    }

    return (
        <div className={wrapperClass}>
            <label htmlFor={name}>{label}</label>
            <div className="field">
                <input
                type={type}
                name={name}
                className="form-control"
                placeholder={placeholder}
                value={value}
                onChange={onChange}/>
                {error && <div className="alert alert-danger">{error}</div>}
            </div>
        </div>
    );
}

TestInput.defaultProps ={
    type: "text"
}