【发布时间】:2019-10-31 01:25:24
【问题描述】:
我正在使用自述文件中指出的常见用例:
const Desktop = props => (
<Responsive {...props} minWidth={1680} maxWidth={2560} />
)
const LaptopL = props => (
<Responsive {...props} minWidth={1440} maxWidth={1679} />
)
...
我有一个道具(bottleState),我试图将它传递给响应式组件(例如桌面)内的特定组件:
const WineHeader = ({ bottleState }) => (
<HeaderCard>
<Desktop>
<WineBox />
<WineBackgroundBox />
<VineyardBackgroundBox />
<WineInfoContainer>
<LeftContainer>
<WineTypeBox bottleState={bottleState} />
<WineTitleBox bottleState={bottleState} />
<WineDescriptionBox bottleState={bottleState} />
</LeftContainer>
<WineProperties />
</WineInfoContainer>
</Desktop>
<LaptopL>
<WineBox />
<WineBackgroundBox />
<VineyardBackgroundBox />
<WineInfoContainer>
<LeftContainer>
<WineTypeBox />
<WineTitleBox />
<WineDescriptionBox />
</LeftContainer>
<WineProperties />
</WineInfoContainer>
</LaptopL>
...
</HeaderCard>
)
WineHeader.propTypes = Object.freeze({
bottleState: PropTypes.object, //eslint-disable-line
})
export default WineHeader
在我试图访问它的上述子组件之一中记录 bottleState 属性时 - 它不可用(日志返回未定义):
const WineTypeBox = ({ bottleState }) => (
<WineTypeStyle>{console.log(bottleState)}</WineTypeStyle>
)
> undefined ---- WineTypeBox.jsx?a13c:36
当我简单地移除 Responsive 组件时,我可以按预期访问 bottleState 道具:
const WineHeader = ({ bottleState }) => (
<HeaderCard>
<WineBox />
<WineBackgroundBox />
<VineyardBackgroundBox />
<WineInfoContainer>
<LeftContainer>
<WineTypeBox bottleState={bottleState} />
<WineTitleBox bottleState={bottleState} />
<WineDescriptionBox bottleState={bottleState} />
</LeftContainer>
<WineProperties />
</WineInfoContainer>
...
</HeaderCard>
)
登录到控制台时返回bottleState对象:
{wineCollection: "Classics", wineType: "Semi Sweet Red", bottleName: "Khvanchkara", bottleImage: Array(1), bottleNoteText: "<p>test</p>", …}
bottleImage: ["http://localhost/uploads/bottle.png"]
bottleName: "Khvanchkara"
bottleNoteText: "<p>test</p>"
temperatureHigh: null
vintage: null
volume: null
wineCollection: "Classics"
wineType: "Semi Sweet Red"
__proto__: Object ---- WineTypeBox.jsx?a13c:36
任何想法为什么会这样?我尝试在 WineHeader 功能组件中定义桌面功能,因为这是我从 this.props 中拉出 bottleState 道具的功能,但这不会改变行为;在桌面组件的返回语句之前抛出一个调试器时,我可以清楚地看到正在传入的 bottleState prop,我什至不需要传入它,因为我直接将它传递给嵌套在 DOM 树下方的其他组件,而没有桌面组件未包装它们时的任何问题,但我需要访问此道具的其他组件嵌套在桌面组件内的事实导致道具因某种原因被阻止。任何帮助是极大的赞赏。谢谢,
科里
【问题讨论】:
-
有什么原因你不能使用 react-responsive 的上下文来传递道具?
-
@tgerr 所以这是我的第一个方法 - 我尝试实现自述文件示例并不断收到错误:'Uncaught ReferenceError: ResponsiveContext is not defined'
-
我试图将代码 sn-ps 放在这里,但它们似乎在 cmets 中格式不正确,知道为什么没有定义 ResponsiveContext - 我正在像这样导入它:
import Responsive, { Context as ResponsiveContext } from 'react-responsive' -
另外,它不应该在没有上下文 API 的情况下工作吗?
-
你能测试一下吗:1.给第二个
<WineTypeBox />添加props。 2. 添加<Default ...>包装器,以及 3. 使用WineHeader = props =>和<WineTypeBox {...props} />传递道具,谢谢
标签: javascript reactjs