Javascript 反应全局分量
我来自vue.js背景,最近刚开始研究react 我有一个组件:PageContent.jsx,我希望使用它而不必不断地导入它,以便能够在渲染函数(jsx)中使用它 在vue中,可以通过以下方式对组件进行全球化:Javascript 反应全局分量,javascript,reactjs,components,create-react-app,Javascript,Reactjs,Components,Create React App,我来自vue.js背景,最近刚开始研究react 我有一个组件:PageContent.jsx,我希望使用它而不必不断地导入它,以便能够在渲染函数(jsx)中使用它 在vue中,可以通过以下方式对组件进行全球化: Vue.component(componentName, componentObject) react中有类似的东西吗?嗯,react中没有任何类型的“全局”组件。每个组件都必须作为道具导入或传递。如果要避免向每个文件添加导入,您有几个选项: 1) 创建呈现PageContent和包
Vue.component(componentName, componentObject)
react中有类似的东西吗?嗯,react中没有任何类型的“全局”组件。每个组件都必须作为道具导入或传递。如果要避免向每个文件添加导入,您有几个选项: 1) 创建呈现
PageContent
和包装组件的
import PageContent from './PageContent';
const withPageContent = WrappedComponent => {
return class extends React.Component {
render () {
return (
<PageContent>
<WrappedComponent />
</PageContent>
)
}
}
};
export default withPageContent;
// Usage
import withPageContent from './withPageContent';
class MyComponent extends React.Component {
render () {
return (
<div>
I'm wrapped in PageContent!
</div>
)
}
}
export default withPageContent(MyComponent);
我非常同意他的回答。
但是,如果您需要另一种方法,您可以使用。您可以在应用程序根目录或其他嵌套组件树中声明要轻松访问的组件集合
下面是一个使用useContext
hook的示例,但hook不是必须的。该结构是标准的create-react-app
结构
我们希望全局访问的组件-src/deep/Header.js:
函数头(){
返回(
我是全球的一员
);
}
导出默认标题;
上下文创建-src/global-components-context.js:
从“React”导入React;
const MyContext=React.createContext(null);
导出默认MyContext;
全局组件的分组-src/global-components.js:
从“./deep/Header”导入标头;
常量上下文值={
标题,
};
导出默认上下文值;
app init文件-src/index.js:
从“React”导入React;
从“react dom”导入react dom;
从“./App”导入应用程序;
从“/global components context”导入MyContext;
从“./global component”导入contextValue;
ReactDOM.render(
,
document.getElementById('root'))
);
在不导入组件的情况下使用组件-src/App.js:
从'react'导入{useContext};
从“/global components context”导入globalComponent;
函数App(){
const Context=useContext(globalComponent);
返回(
);
}
导出默认应用程序;
我认为这是react中最具全球性的组件。请注意,您仍然需要在希望使用全局组件的任何位置导入上下文
import PageContent from './PageContent';
const withPageContent = WrappedComponent => {
return class extends React.Component {
render () {
return (
<PageContent>
<WrappedComponent />
</PageContent>
)
}
}
};
export default withPageContent;
// Usage
import withPageContent from './withPageContent';
class MyComponent extends React.Component {
render () {
return (
<div>
I'm wrapped in PageContent!
</div>
)
}
}
export default withPageContent(MyComponent);
还有一个免责声明,全局组件很难测试,而且常常难以推理。我相信这就是为什么现在有标准的解决方案
希望我能帮上忙谢谢你的例子,尽管我真的在寻找一些东西来减少每个组件所需的进口量。看起来我不得不接受这个事实,但是如果我想和reactYeah一起工作,你仍然需要导入一些东西,但是有一些技巧可以让你更轻松。您可以使用使导入路径更小并删除文件扩展名。您还可以创建一个导出多个组件的文件,然后可以在一行上导入多个组件,如下所示:
import{Button,Input,Icon}来自“utils/inputs”代码>