使用React.cloneElement时如何将道具传递给样式组件

时间:2019-10-03 18:27:19

标签: reactjs styled-components

我有一个包装器组件和许多嵌套组件。我正在使用topMargin将新的道具React.cloneElement传递给嵌套组件,但styled-components似乎完全忽略了它们。

在示例中,我在StyledInnerInner中记录道具。产生的道具完全不同。我想念什么?

此处的示例: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
}

1 个答案:

答案 0 :(得分:2)

您的Inner组件收到topMargin道具,但是他们没有将道具传递给StyledInner

const Inner = props => {
  console.log(props)
  return <StyledInner topMargin={props.topMargin}>{props.children}</StyledInner>
}