使用状态与TypeScript作出反应

Mac*_* S. 17 javascript typescript reactjs

我是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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

错误说:"[ts]属性'playOrPause'在'ReadOnly <{}>'类型中不存在.

我试图将playOrPause属性声明为一种字符串,但它不起作用.我在这里错过了什么才能让它发挥作用?

小智 51

如果有人想知道如何在带有钩子的功能组件中实现它(而不是在类中)

const [value, setValue] = useState<number>(0);
Run Code Online (Sandbox Code Playgroud)

useState 是一个泛型函数,这意味着它可以接受类型参数。这个类型参数将告诉 TypeScript 哪些类型可以接受该状态。

  • 这仅对react中的函数有效,对类无效。我已经吸取了这个惨痛的教训。 (5认同)

fel*_*osh 35

您需要声明您的组件正在使用Statecript接口,它由Typescript的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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 泛型位置有一个含义,第一个位置应该表示props类型,第二个是状态。 (3认同)
  • 如果状态在构造函数`state = { playOrPause: 'Play' }` 之外声明,则打字稿不会根据`IState` 验证它。为什么会这样? (3认同)
  • @RahulYadav 如果你这样做,你可以只做 `state: IState = {...}` 并将其从通用道具中删除。就会被推断出来。 (2认同)