我有一个包装器组件和许多嵌套组件。我正在使用topMargin
将新的道具React.cloneElement
传递给嵌套组件,但styled-components
似乎完全忽略了它们。
在示例中,我在StyledInner
和Inner
中记录道具。产生的道具完全不同。我想念什么?
此处的示例:https://codesandbox.io/s/happy-maxwell-hgkp1
import React from "react";
import ReactDOM from "react-dom";
import styled from 'styled-components'
const StyledOuter = styled('div')`
background:blue;
padding: 1rem;
`
const Outer = props => {
const proppedChildren = React.Children.map(
props.children, (child)=>
React.cloneElement(child, { topMargin: '10px'})
)
return <StyledOuter>{proppedChildren}</StyledOuter>
}
const StyledInner = styled('div')`
background: red;
margin-top: ${props => {
console.log(props)
return props.topMargin || '50px'
}};
`
const Inner = props => {
console.log(props)
return <StyledInner>{props.children}</StyledInner>
}
function App() {
return (
<div className="App">
<Outer>
<Inner>
This is where the magic happens.
</Inner>
<Inner>
Here too.
</Inner>
</Outer>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
记录道具的结果如下:
在<Inner />
{
children: "Here too.",
topMargin: "10px"
}
在<StyledInner />
{
children: "Here too.",
forwardedComponent: Object,
forwardedRef: null,
theme: Object
}
答案 0 :(得分:2)
您的Inner
组件收到topMargin道具,但是他们没有将道具传递给StyledInner
const Inner = props => {
console.log(props)
return <StyledInner topMargin={props.topMargin}>{props.children}</StyledInner>
}