Jay*_*ffe 4 javascript reactjs
我只是尝试使用带有反应的简单 HOC。这是功能:
import React from "react"
const withOptions = (WrappedComponent) => {
return class extends React.Component {
render() {
return <WrappedComponent { ...this.props } />
}
}
}
export default withOptions
Run Code Online (Sandbox Code Playgroud)
问题似乎出在我导出/导入它的方式上。
以简单的方式导入和使用,它的工作原理:
import withOptions from "./Options"
...
class BilanClimatique extends React.Component{
...
}
const StyledBilanClimatique = withStyles(styles)(BilanClimatique)
export default withOptions(StyledBilanClimatique)
Run Code Online (Sandbox Code Playgroud)
但是如果我使用像 index.js 这样的中间文件
import withOptions from "./Options"
export {
withOptions
}
Run Code Online (Sandbox Code Playgroud)
并像这样将其导入到我的组件中
import {
withOptions
} from "./index"
Run Code Online (Sandbox Code Playgroud)
这是我得到的
有人可以帮助我理解这一点吗?
编辑 :
我发现使用 HOC 的组件是从与 HOC 相同的文件中导入的:
import withOptions from "./Options"
import BilanClimatique from "./BilanClimatique"
export {
withOptions,
BilanClimatique
}
Run Code Online (Sandbox Code Playgroud)
这导致了问题,但我不明白为什么......这是一个有问题的沙箱https://codesandbox.io/s/r074735yvo
dub*_*bes 10
这似乎是提升“出口”的问题。从我所看到的,imports被吊起,但我看不到任何类似的东西exports。
导致问题的流程(codeandbox):
应用程序.js:
import { BilanClimatique } from "./components/index";
Run Code Online (Sandbox Code Playgroud)
./components/index.js:
// just using the "re-export" shortcut
export { default as BilanClimatique } from "./BilanClimatique";
export { default as withOptions } from "./Options";
Run Code Online (Sandbox Code Playgroud)
./components/BilanClimatique.js:
import { withOptions } from "./index";
Run Code Online (Sandbox Code Playgroud)
./components/Options.js:
const withOptions = WrappedComponent => {
return ... //snipped code
export default withOptions;
Run Code Online (Sandbox Code Playgroud)
当 App.js 向 index.js 询问 BilanClimatique 时,它反过来向相同的index.js询问withOptions. 但是由于导出似乎没有被提升,index.js 还没有使 withOptions 可用。
怎么解决:
在 ./components/index.js 中,根据您的依赖更改导出顺序:
// just using the "re-export" shortcut
export { default as withOptions } from "./Options";
export { default as BilanClimatique } from "./BilanClimatique";
Run Code Online (Sandbox Code Playgroud)
我不会推荐它。它非常脆弱。
即在 ./components/BilanClimatique.js 中:
import withOptions from "./Options";
Run Code Online (Sandbox Code Playgroud)
除非您遇到 #2 的问题,否则我个人会推荐 #2 而非 #3。
| 归档时间: |
|
| 查看次数: |
2973 次 |
| 最近记录: |