英文:
Wrapped component not rendering
问题
我正在尝试根据条件来渲染一个组件。我正在使用包装函数来实现这个目标。然而,当条件满足时,组件没有渲染。
App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Component from "./Component";
import Wrapper from "./Wrapper";
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/component" element={<Component />} />
<Route path="/wcomponent" element={Wrapper(Component)} />
</Routes>
</BrowserRouter>
);
}
Wrapper.js
const { useState } = require("react");
const Wrapper = (WrappedComp) => {
const AuthComponent = (props) => {
const [value, setValue] = useState(true);
if (value) return <WrappedComp {...props} />;
else return <div>另一个组件</div>;
};
return AuthComponent;
};
export default Wrapper;
Component.js
const Component = () => {
return <div>第一个组件</div>;
};
export default Component;
英文:
I am trying to render a component based on a condition. I am using wrapper function to do so. However the component is not rendering when condition is met.
App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Component from "./Component";
import Wrapper from "./Wrapper";
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/component" element={<Component />} />
<Route path="/wcomponent" element={Wrapper(Component)} />
</Routes>
</BrowserRouter>
);
}
Wrapper.js
const { useState } = require("react");
const Wrapper = (WrappedComp) => {
const AuthComponent = (props) => {
const [value, setValue] = useState(true);
if (value) return <WrappedComp {...props} />;
else return <div> The other component </div>;
};
return AuthComponent;
};
export default Wrapper;
Component.js
const Component = () => {
return <div> The first Component </div>;
};
export default Component;
答案1
得分: 1
<Variable />
在这种情况下,你的包装器是一个HOC(高阶组件)。
基本上,你可以将其看作是一个带有参数的函数(Wrapper(Component))。你需要做的是定义一个变量并使用这个包装器变量作为组件(组件应以大写形式定义):
const WrapperComp = Wrapper(Component);
<BrowserRouter>
<Routes>
<Route path="/component" element={<Component />} />
<Route path="/wcomponent" element={<WrapperComp />} />
</Routes>
</BrowserRouter>
英文:
If you want to use an Variable as a component wrap it with arrows like
<Variable />
In this case, your Wrapper is a HOC(Higher order component).
Basically, you can see it(Wrapper(Component)) is a function with param. All the things you need is define a variable with this Wrapper. and use this variable like a component (component should define in Capitalize form)
const WrapperComp = Wrapper(Component);
<BrowserRouter>
<Routes>
<Route path="/component" element={<Component />} />
<Route path="/wcomponent" element={<WrapperComp />} />
</Routes>
</BrowserRouter>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论