Typescript input onchange event.target.value

后端 未结 11 938
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 21:25

In my react and typescript app, I use: onChange={(e) => data.motto = (e.target as any).value}.

How do I correctly define the typings for the class, s

11条回答
  •  没有蜡笔的小新
    2020-11-28 22:11

    the correct way to use in TypeScript is

      handleChange(e: React.ChangeEvent) {
        // No longer need to cast to any - hooray for react!
        this.setState({temperature: e.target.value});
      }
    
      render() {
            ...
            
            ...
        );
      }
    

    Follow the complete class, it's better to understand:

    import * as React from "react";
    
    const scaleNames = {
      c: 'Celsius',
      f: 'Fahrenheit'
    };
    
    
    interface TemperatureState {
       temperature: string;
    }
    
    interface TemperatureProps {
       scale: string;
    
    }
    
    class TemperatureInput extends React.Component {
      constructor(props: TemperatureProps) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {temperature: ''};
      }
    
      //  handleChange(e: { target: { value: string; }; }) {
      //    this.setState({temperature: e.target.value});  
      //  }
    
    
      handleChange(e: React.ChangeEvent) {
        // No longer need to cast to any - hooray for react!
        this.setState({temperature: e.target.value});
      }
    
      render() {
        const temperature = this.state.temperature;
        const scale = this.props.scale;
        return (
          
    Enter temperature in {scaleNames[scale]}:
    ); } } export default TemperatureInput;

提交回复
热议问题