是否可以不使用JSX而使用React Hooks API(在打字稿中)

When translating JSX version React Hooks API demo into the one without JSX, following react-without-jsx, I got the following code

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吗?如果有可能,我们该怎么做?

评论