reactjs - 如何创建一个新的 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-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
解决方案
更新
如果你真的想使用类,你可以注入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>;
}
推荐阅读
- python - Opencensus Python gRPC 的“异常迭代请求”
- c - Sprintf 正在连接值
- java - 在一维战舰游戏Java中实现第二艘船
- postgresql - 如何使用 Postgres 创建 trigram 或 ngram 单词
- node.js - Vercel.com 托管:开发和生产 URL
- javascript - 仅在子组件中使用道具是不好的做法吗?没有自己状态的子组件
- c - 在 C 中将 uint_8* 转换为任何类型,比如“double”或结构?
- reactjs - 如果 Apollo GraphQL 令牌无效或已过期,则 NextAuth.js 注销
- php - 正则表达式匹配特定字符串而没有其他字符串
- python - Python - 保存循环输出