Using state in react with TypeScript

前端 未结 3 893
说谎
说谎 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 {
    
      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!

提交回复
热议问题