【问题标题】:How can I pass props to base component in styled-component?如何将道具传递给样式组件中的基础组件?
【发布时间】:2019-03-31 22:03:30
【问题描述】:

举个例子,假设我有一个可以像这样接收 props 的组件:

const testComponent = (props: {isBold: boolean}) => {
   if(props.isBold)
     return <strong><div>hello</div></strong>
   return <div>hello</div>
    
}

在这种情况下,我的示例组件可以接受道具,结果取决于给它的道具。

现在,如果我在 styled-components 中扩展这个组件,我如何将我的 props 传递到基础组件中?这个想法是这样的:

const styledTestComponent = styled(testComponent({isBold: true}))`
    width: 100%;
    opacity: 0.5
    /* etc etc... */
`

好吧,显然行不通。这部分会失败:styled(testComponent({isBold: true}))

但我的想法是,我想做的是使用 CSS 来设置组件的特定实例的样式。所以在这种情况下,我需要将预定义的 props 传递给基础组件 testComponent

我怎样才能做到这一点?

更新:

我想出了一个简单的例子来说明这个问题。下面的代码尝试将 react 组件 MyCustomImage 设置为样式组件 StyledMyCustomImage。当它运行时,您可以看到StyledMyCustomImage 确实将自己呈现为MyCustomImage。但是,没有应用 CSS 样式。

const MyCustomImage = props => (
  <img
    src={`https://dummyimage.com/${props.width}x${props.height}/619639/000000`}
  />
);

const StyledMyCustomImage = styled(MyCustomImage)`
  border: 2px dotted red;
`;

function App() {
  return (
    <div className="App">
      <h3>Test passing props from styled component to base component</h3>
      <StyledMyCustomImage width="600" height="400" />
    </div>
  );
}

我为此演示创建了一个沙盒:https://codesandbox.io/s/k21462vjr5

更新 2:

哦!感谢@SteveHolgado 的回答,我已经开始工作了!我不知道样式化组件会将 CSS 作为道具传递给它的基础组件!这是添加类名后的代码以供将来参考:

const MyCustomImage = props => (
  <img
    src={`https://dummyimage.com/${props.width}x${props.height}/619639/000000`}
    className={props.className}
  />
);

const StyledMyCustomImage = styled(MyCustomImage)`
  border: 2px dotted red;
`;

工作演示的悲伤盒:https://codesandbox.io/s/j4mk0n8xkw

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    试试这个,应该可以的

    const StyledTestComponent = styled(testComponent)`
        width: 100%;
        opacity: 0.5
        /* etc etc... */
    `
    

    并以这种方式将道具传递给实例。

    <StyledTestComponent isBold />
    

    欢迎反馈。我还没有检查过它是否有效,但感觉它会有效

    注意:我检查过,它正在工作。应该适合你。

    【讨论】:

    • 我刚试了一下。虽然 props 确实被传递,但 StyledTestComponent 中的样式并没有被应用。事实上,当我查看页面的源代码时,页面上根本没有那些样式。
    • 我用一个例子更新了我的问题来说明我的问题。
    【解决方案2】:

    当您像这样使用styled 函数时,您的包装组件将获得一个名为 className 的道具,您需要将其应用于您希望样式影响的元素:

    const testComponent = (props) => {
      return <div className={props.className}>hello</div>
    }
    

    您将可以访问您样式中的所有道具,您可以像这样使用它们:

    const styledTestComponent = styled(testComponent)`
      width: 100%;
      opacity: 0.5;
      font-weight: ${props => props.isBold ? "bold" : "normal"};
    
      /* etc etc... */
    `
    

    【讨论】:

    • 谢谢!我已经让它工作了!我还在示例代码中用您的回答更新了我的问题。
    • 提醒一下@Carven,您不应该将答案放在问题中并将答案留在页面上,因为这会使用户感到困惑。
    猜你喜欢
    • 2019-09-23
    • 2020-10-28
    • 2022-11-15
    • 2017-10-20
    • 2022-01-03
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多