如何创建一个带有null返回值但仍然访问钩子的新React组件

时间:2020-03-10 05:55:39

标签: reactjs

可以像在创建新的javascript对象时一样,在代码中创建一个新的组件,而不是在dom中放入react组件?

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返回null,但不允许我调用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-0h2uz处创建了一个沙箱,但是super()给出了错误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

enter image description here

1 个答案:

答案 0 :(得分:0)

更新

如果您真的想使用类,可以在类构造函数中注入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>;
}