是否可以在不使用JSX的情况下使用React Hooks API(在打字稿中)

问题描述 投票:1回答:1

[将JSX版本的React Hooks API demo转换为没有JSX的版本时,react-without-jsx之后,我得到了以下代码

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

export function test() {
  ReactDOM.render(Count(), document.getElementById('main'));
}

export function Count() {
  const e = React.createElement;
  const [count, setCount] = useState(0);
  const button = e('button', {
    onClick: () => {
      setCount(count + 1);
    },
  });
  return e('div', null, e('p', `You clicked ${count} times`), button);
}

但是,在浏览器中运行此代码时,出现以下错误

react.development.js:1551 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/warnings/invalid-hook-call-warning.html for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js:1551)
    at Object.useState (react.development.js:1582)
    at Count (Count.ts:10)
    at Object.test (Count.ts:5)
    at main (index.ts:4)
    at Object../src/index.ts (index.ts:6)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83
resolveDispatcher @ react.development.js:1551
useState @ react.development.js:1582
Count @ Count.ts:9
test @ Count.ts:4
main @ index.ts:3
./src/index.ts @ index.ts:6
__webpack_require__ @ bootstrap:18

如果使用JSX,则上面的示例可以正常工作。

所有功能组件的示例似乎都基于JSX。那么可以在没有JSX的情况下使用React Hook吗?如果可能的话,我们该怎么做?

reactjs typescript react-hooks jsx
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.