使用 React.cloneElement 时如何将 props 传递给 styled-component
How to pass props to styled-component when using React.cloneElement
我有一个包装组件和一些嵌套组件。我正在将新道具 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);
记录 props 结果如下:
在 <Inner />
{
children: "Here too.",
topMargin: "10px"
}
在 <StyledInner />
{
children: "Here too.",
forwardedComponent: Object,
forwardedRef: null,
theme: Object
}
您的 Inner
组件收到 topMargin 道具,但随后他们没有将道具传递给 StyledInner
const Inner = props => {
console.log(props)
return <StyledInner topMargin={props.topMargin}>{props.children}</StyledInner>
}
我有一个包装组件和一些嵌套组件。我正在将新道具 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);
记录 props 结果如下:
在 <Inner />
{
children: "Here too.",
topMargin: "10px"
}
在 <StyledInner />
{
children: "Here too.",
forwardedComponent: Object,
forwardedRef: null,
theme: Object
}
您的 Inner
组件收到 topMargin 道具,但随后他们没有将道具传递给 StyledInner
const Inner = props => {
console.log(props)
return <StyledInner topMargin={props.topMargin}>{props.children}</StyledInner>
}