首页 > 解决方案 > 如何创建一个新的 React 组件返回 null 但仍然访问钩子

问题描述

可以在代码中创建一个新组件,而不是在 dom 中放置一个反应组件,就像创建一个新的 javascript 对象一样?

import * as React from "react";
import Nodetest from "./nodetest";

export default function App() {
  const makeNewNode = () => {
    const NewNode = new Nodetest();
    NewNode.makelog();
  };

  return <button onClick={makeNewNode}>Make New node</button>;
}

Nodetest有一个空返回,但不允许我调用 useContext 钩子。

import { Component, useContext } from "react";
import { Dispatch, DRAW } from "./global";

class Nodetest extends Component {
  test: string;
  dispatch: any;

  constructor() {
    super();
    this.test = "hello";
    this.dispatch = useContext(Dispatch);
  }

  makelog = () => {
    this.dispatch({ type: DRAW, value: Date.now() });
    console.log("new log");
  };

  render() {
    return null;
  }
}

export { Nodetest };

更新

我在这里创建了一个沙箱https://codesandbox.io/s/eager-wiles-0h2uzsuper()给出了错误index.d.ts(449, 21): An argument for 'props' was not provided.并单击按钮导致Invalid hook call. Hooks can only be called inside of the body of a function component

在此处输入图像描述

标签: reactjs

解决方案


更新

如果你真的想使用类,你可以注入dispatch类构造函数。

不是 100% 确定这是否可行,但您可以尝试!

// Nodetest.ts
export default class Nodetest {
  test: string;
  dispatch: any;

  constructor(dispatch) {
    this.test = "hello";
    this.dispatch = dispatch;
  }

  makelog = () => {
    this.dispatch({ type: DRAW, value: Date.now() });
    console.log("new log");
  };
}
import * as React from "react";
import { Dispatch, DRAW } from "./global";
import Nodetest from "./Nodetest";

export default function App() {
  const dispatch = React.useContext(Dispatch);

  const makeNewNode = () => {
    const NewNode = new Nodetest(dispatch);
    NewNode.makelog();
  };

  return <button onClick={makeNewNode}>Make New node</button>;
}


老的

您只能将 React 钩子与功能组件一起使用。从您提供的最好的示例中,您可以做的是:

import * as React from "react";
import { Dispatch, DRAW } from "./global";

export default function App() {
  const dispatch = React.useContext(Dispatch);

  cosnt makelog = () => {
    dispatch({ type: DRAW, value: Date.now() });
    console.log("new log");
  };

  const makeNewNode = () => {
    makelog();
  };

  return <button onClick={makeNewNode}>Make New node</button>;
}

推荐阅读