簡體   English   中英

使用狀態與 TypeScript 反應

[英]Using state in react with TypeScript

我是 TypeScript 的新手。 我在渲染方法中顯示 this.state.something 或將其分配給函數中的變量時遇到問題。

看看最重要的一段代碼:

interface State {
    playOrPause?: string;
}

class Player extends React.Component {
    constructor() {
        super();

        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>
        );
    }
}

錯誤說:“[ts] 屬性 'playOrPause' 在類型 'ReadOnly<{}>' 上不存在。

我試圖將 playOrPause 屬性聲明為一種字符串,但它不起作用。 我在這里缺少什么才能使它工作?

您需要聲明您的組件正在使用 State 接口,它由 Typescript 的泛型使用。

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>
    );
  }
}

如果有人想知道如何使用鈎子實現它:

const [value, setValue] = useState<number>(0);

useState 是一個泛型函數,這意味着它可以接受一個類型參數。 這個類型參數將告訴 TypeScript 哪些類型可以接受這種狀態。

在我的情況下(使用 TypeScript,狀態值實際上是一個布爾值)我遇到了同樣的問題,我通過將我想標記為輸出的狀態值傳遞給 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>
    )
  }
}

只需使用屬性、類型聲明接口或類型,並將其注釋為狀態。 ? 意思是可選的:

interface ITestProps {}

interface ITestState {
  playOrPause?: string;
}

class Player extends React.Component<ITestProps, ITestState> {

  state = {
     playOrPause: 'Play'
  };
  

  render() {
    return // your code here
}

您可以根據需要為上面的接口添加更多值,如果您需要相同的狀態將其傳遞給子組件,您只需要創建一個帶有.d.ts的文件就可以了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM