TypeScript:对象可能为“ null”

时间:2019-12-10 14:46:56

标签: javascript reactjs typescript

我正在尝试将react项目转换为TypeScript。下面的代码是一个输入字段,用于计算正在输入的字符数。

在renderCharactersLeft函数中,出现以下错误:

enter image description here

这并不是真的让我感到惊讶,因为默认状态'charsLeft'设置为null,但是我想知道如何在TypeScript中绕过或解决此消息?

import React from "react";

interface CharCountInputProps {
  value: string;
  type: string;
  name: string;
  maxChars: number;
  onChange: any;
}

interface CharCountInputState {}

class CharCountInput extends React.Component<
  CharCountInputProps,
  CharCountInputState
> {
  state = {
    charsLeft: null
  };

  componentDidMount() {
    this.handleCharCount(this.props.value);
  }

  handleCharCount = (value: string) => {
    console.log(value);
    const { maxChars } = this.props;
    const charCount = value.length;
    const charsLeft = maxChars - charCount;
    this.setState({ charsLeft });
  };

  changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ [event.target.name]: event.target.value } as Pick<
      CharCountInputState,
      keyof CharCountInputState
    >);
    this.handleCharCount(event.target.value);
    this.props.onChange(event);
  };

  renderCharactersLeft = () => {
    const { charsLeft } = this.state;

    let content;
    if (charsLeft >= 0) {
      content = <span>{`characters left: ${charsLeft}`}</span>;
    } else if (charsLeft != null && charsLeft < 0) {
      const string = charsLeft.toString().substring(1);
      content = <span>{`too many characters: ${string}`}</span>;
    } else {
      content = null;
    }
    return content;
  };

  render() {
    const { value, type, name } = this.props;

    return (
      <>
        <input
          onChange={this.changeHandler}
          value={value}
          type={type}
          name={name}
        />
        {this.renderCharactersLeft()}
      </>
    );
  }
}

export default CharCountInput;

1 个答案:

答案 0 :(得分:4)

您可以将空检查添加到if语句中,如下所示:

if (charsLeft !== null && charsLeft >= 0) {

或将charsLeft的初始状态设置为非null(例如,道具中的maxChars)