直接上代码
App.js
import React from "react";
import useTest from "./useTest";
function App(tag, attr, children) {
const a = useTest(1); //单纯这么写会失败
return React.createElement(tag, attr, children);
}
export default App;
useTest.js
import React, { useRef, useEffect } from "react";
export default function useTest(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
index.js
import ReactDOM from "react-dom";
import App from "./App";
const app = App("input", { type: "text" });
ReactDOM.render(app, document.getElementById("root"));
问题不在于我使用了app=App()的方式初始化react
问题出在App.js 中直接使用hooks会失败,因为react会默认认为App.js是一个常规组件,无法使用hooks,即只有hooks组件才能调用hooks组件,无状态组件和class组件都不行,即此处App.js必须利用至少一个hooks的api才行
修改后的代码
App.js (updated)
import React,{useState} from "react";
import useTest from "./useTest";
function App(tag, attr, children) {
const a = useTest(1); //单纯这么写会失败
const [t,setT]=useState(0); //至少用一个hooks才行
return React.createElement(tag, attr, children);
}
export default App;