Using state in react with TypeScript

前端 未结 3 925
说谎
说谎 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 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 {
      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 (
          
    Hello, {this.props.name}!
    Toggle state is: {String(this.state.toggle)}
    ) } }

提交回复
热议问题