我是打字新手.我显示这个有问题.状态渲染方法中的某个内容,或将其指定给函数中的某个变量.

看看最重要的一段代码:

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

The errors says: "[ts] Property 'playOrPause' does not exist on type 'ReadOnly<{}>'.

我试图将playOrPause属性声明为一种字符串类型,但没有成功.

推荐答案

您需要声明您的组件正在使用状态接口,它由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>
    );
  }
}

Reactjs相关问答推荐

props 可以在Reaction中锻造吗?

包装组件可以避免子组件重新渲染.?

在Reaction+Redux+RTKQuery中对API调用进行排序

导致useState中断的中断模式

FireBase未与Reaction应用程序连接

使用REACT-RUTER-DOM链接仅更新一个搜索参数

使用Ionic 7和React 18,如何访问历史对象以在页面之间导航?

取消 Select 较高组件中的所有行

StrictMode+SetInterval=双重渲染(即使使用useEffect清理)

为什么我的react 简单计时器项目不起作用?

React-router动态路径

如何根据ReactJS中元素列表中的布尔值仅显示一次值

Next.js 和理智 | npm run build 时预渲染页面/时发生错误

如何在next.js 13中仅在主页导航栏上隐藏组件?

VideoSDK api 不使用更新状态

如何防止开发人员使用 ESLint 在 React 项目中使用特定的钩子?

使用带有搜索字符串的全局过滤器时如何在 React-Table 中进行精确匹配?

响应式媒体 React Tailwind

axios post方法中的请求失败,状态码为500错误

将 C# Razor 条件块转换为 React.js 代码