Using state in react with TypeScript

前端 未结 3 820
说谎
说谎 2020-12-09 14:12

I am new to TypeScript. I\'ve got a problem with displaying this.state.something inside the render method or assigning it to a variable inside a function.

Have a loo

相关标签:
3条回答
  • 2020-12-09 14:52

    Just declare interface or type with property, types, and annotate it to state. the ? mean optional:

    interface ITestProps {}
    
    interface ITestState {
      playOrPause?: string;
    }
    
    class Player extends React.Component<ITestProps, ITestState> {
    
      state = {
         playOrPause: 'Play'
      };
      
    
      render() {
        return // your code here
    }
    

    You can add more value as per your need to interface above if then you need the same state to pass it to child component you just need to create a file with .d.ts and you should be good to go!

    0 讨论(0)
  • 2020-12-09 14:54

    You need to declare that your component is using the State interface, it used by Typescript's Generics.

    interface IProps {
    }
    
    interface IState {
      playOrPause?: string;
    }
    
    class Player extends React.Component<IProps, IState> {
      // ------------------------------------------^
      constructor(props: IProps) {
        super(props);
    
        this.state = {
          playOrPause: 'Play'
        };
      }
    
      render() {
        return(
          <div>
            <button
              ref={playPause => this.playPause = playPause}
              title={this.state.playOrPause} // in this line I get an error
            >
              Play
            </button>
          </div>
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-09 15:01

    In my case ( working with TypeScript, and the state value was actually a boolean ) I've had the same problem, I've fixed it by passing the state value I wanted to mark as output to String():

    import React, { Component } from 'react';
    
    interface ITestProps {
      name: string;
    }
    
    interface ITestState {
      toggle: boolean;
    }
    
    class Test extends Component<ITestProps, ITestState> {
      constructor(props: ITestProps) {
        super(props);
    
        this.state = {
          toggle: false,
        };
    
        this.onClick = this.onClick.bind(this);
      }
    
      onClick() {
        this.setState((previousState, props) => ({
          toggle: !previousState.toggle,
        }));
      }
    
      render() {
        return (
          <div>
            Hello, {this.props.name}!
            <br />
            Toggle state is: {String(this.state.toggle)}
          </div>
        )
      }
    }
    
    0 讨论(0)
提交回复
热议问题