样式化组件.attrs-reaction不识别道具
我正在尝试将一个道具传递到我的样式组件中。它按预期工作,但Reaction引发已知的"UNKNOWN PROP"错误。
我在许多地方尝试使用扩散运算符,但都不起作用。
我要将道具传递给的已设置样式的组件:
const StyledBackgroundImage = styled(BackgroundImage).attrs(({minHeight}) => ({
minHeight: minHeight || "60vh",
}))`
min-height: ${({minHeight}) => minHeight};
/* ... */
`;
父组件:
const ImageWithText = ({imageData, minHeight, children}) => {
return (
<StyledBackgroundImage
Tag="div"
backgroundColor={'#000000'}
fluid={imageData}
minHeight={minHeight}
>
{children}
</StyledBackgroundImage>
)
}
以及我如何在页面上使用它:
<ImageWithText imageData={data.headerBackgroundImage.childImageSharp.fluid} minHeight='50vh'>
我希望它能工作,确实能工作,但不是没有以下错误:
Warning: React does not recognize the `minHeight` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `minheight` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
in div (created by BackgroundImage)
in BackgroundImage (created by Context.Consumer)
in StyledComponent (created by ImageWithText__StyledBackgroundImage)
in ImageWithText__StyledBackgroundImage (at ImageWithText.js:32)
in ImageWithText (at pages/index.js:20)
in section (created by Context.Consumer)
in StyledComponent (created by LayoutComponents__Section)
in LayoutComponents__Section (at pages/index.js:19)
in main (at layout.js:10)
in Layout (at pages/index.js:17)
in IndexPage (created by HotExportedIndexPage)
in AppContainer (created by HotExportedIndexPage)
in HotExportedIndexPage (created by PageRenderer)
in PageRenderer (at json-store.js:93)
in JSONStore (at root.js:51)
in RouteHandler (at root.js:73)
in div (created by FocusHandlerImpl)
in FocusHandlerImpl (created by Context.Consumer)
in FocusHandler (created by RouterImpl)
in RouterImpl (created by Context.Consumer)
in Location (created by Context.Consumer)
in Router (created by EnsureResources)
in ScrollContext (at root.js:64)
in RouteUpdates (at root.js:63)
in EnsureResources (at root.js:61)
in LocationHandler (at root.js:119)
in LocationProvider (created by Context.Consumer)
in Location (at root.js:118)
in Root (at root.js:127)
in _default (at app.js:65)
解决方案
更新:使用临时道具
使用release 5.1.0可以使用transient props
。这样,您不需要额外的包装,即减少了不必要的代码:
暂态道具是一种传递道具的新模式,这些道具仅由样式化为样式的组件显式使用,并不打算向下传递到更深的组件层。以下是您如何使用它们:
const Comp = styled.div`
color: ${props => props.$fg || 'black'};
`;
render(<Comp $fg="red">I'm red!</Comp>);
请注意道具上的美元符号($)前缀;这将其标记为临时的和样式的-组件知道不将其添加到呈现的DOM元素或在组件层次结构中向下传递它。
新答案应为:
组件:
<ImageWithText
$imageData={data.headerBackgroundImage.childImageSharp.fluid} // notice the '$'
minHeight='50vh'>
样式组件声明:
const StyledBackgroundImage = styled(BackgroundImage).attrs(({$minHeight}) => ({
minHeight: minHeight || "60vh",
}))`
min-height: ${({$minHeight}) => $minHeight}; // notice the '$' before the prop name
/* ... */
`;
相关文章