创建 Liferay React 组件的钩子无效

Invalid hook creating Liferay React component

我正在尝试基于 Liferay 的 Clay 组件创建自定义反应组件。

使用例如只有一个 ClayButton 可以工作,但是一旦我尝试使用钩子(比如 React.useState),浏览器控制台就会告诉我:

Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message

完整的消息告诉我我可能使用了不匹配的 react 和 react-dom 版本。我不是。 根据那里描述的测试,我也没有 2 个不同版本的反应。

我在 https://github.com/ReFl3x0r/liferay-react-component-test 创建了一个最小的示例模块,可以在 Liferay Gradle 工作区中进行测试。

Liferay 论坛中还有一个较早的帖子讨论了此错误,但没有解决方案。 (https://liferay.dev/ask/questions/development/re-lr-7-3-react-portlet-invalid-hook-call)

我做错了什么?

编辑: 试图指出主要代码片段。

第一个CustomButtonFail.es.js:

import React from 'react';

import ClayButton from '@clayui/button';

const CustomButton = () => {

    const [name, setName] = React.useState('test');

    return (
        <ClayButton displayStyle='primary'>
            TEST
        </ClayButton>
    );
}

export default CustomButton;

package.json:

{
    "dependencies": {
        "@clayui/button": "^3.40.0",
        "@clayui/css": "3.x",
        "react": "^16.12.0",
        "react-dom": "^16.12.0"
    },
    "devDependencies": {
         "@liferay/npm-scripts": "47.0.0",
         "react-test-renderer": "^16.12.0"
    },
    "name": "component-test",
    "scripts": {
        "build": "liferay-npm-scripts build"
    },
    "version": "1.0.0"
}

view.jsp包括组件(缩写):

<%@taglib uri="http://liferay.com/tld/react" prefix="react" %>

<div class="react-component-failing">
    <react:component
        module="js/CustomButtonFail.es"
    />
</div>

我终于让它工作了。像这样减少 package.json:

{
  "devDependencies": {
    "@liferay/npm-scripts": "47.0.0"
  },
  "name": "component-test",
  "scripts": {
    "build": "liferay-npm-scripts build"
  },
  "version": "1.0.0"
}

并在模块根目录中添加“.npmbundlerrc”,内容为:

{
  "config": {
      "imports": {
          "frontend-taglib-clay": {
              "@clayui/button": ">=3.40.0",
              "@clayui/css": ">=3.x"
          },
          "@liferay/frontend-js-react-web": {
              "react": ">=16.12.0"
          }
      }
  }
}

成功了。

工作示例位于 https://github.com/ReFl3x0r/liferay-react-component-test/tree/working