【问题标题】:Passing css classes through props to a children component通过道具将css类传递给子组件
【发布时间】:2019-12-04 20:57:13
【问题描述】:

所以,我有一个带有确定类的 css 文件,比如说(class1、class2、class3 等),我需要制作一个展示组件,通过 props 将它们的属性传递给子组件。如果子组件中被调用的名字,那么css类的属性就可以使用了。

【问题讨论】:

  • 我建议您包含一些您尝试过的示例代码并讨论您遇到的问题。
  • their properties to a child component. -- 这些属性从何而来,它们是硬编码在表示组件中,还是传递给它? if the called name in the child component then the properties of the css class are available to use -- 你能进一步解释一下,“子组件中的名称”指的是什么,你想在哪里应用 CSS 类?

标签: html css reactjs styling


【解决方案1】:

props.children = 嵌套在该组件内的组件。我们可以使用React.cloneElement() 来将属性传递给孩子。

const PresentationalComponent = ({ children }) => {
  const hardCodedClassName = '.some-class';
  return (
    <>
        {React.cloneElement(props.children, { className: hardCodedClassName })}
    </>
  )
}

// Usage

<PresentationalComponent>
  <ChildComponent />
</PresentationalComponent>

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2018-01-07
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多