【问题标题】:In React is it possible to pass a prop through a component and have it act as the prop name for a child component在 React 中是否可以通过组件传递一个 prop 并让它充当子组件的 prop 名称
【发布时间】:2021-03-09 05:00:26
【问题描述】:

我正在尝试将道具从父组件传递给子组件,并让该道具充当具有布尔值的道具名称

例如。

App.js

 <Modal
        confirmColor = 'solidPrimary'
      />

OR

 <Modal
        confirmColor = 'solidSuccess'
      />


所需的 Modal.js

const Modal = ({
  confirmColor
}) => {
  return (
       <Button
            {...confirmColor} // Should pass solidPrimary === true //
       />
  )
}

按钮通常会使用像这样的布尔值呈现

      <Button
            solidPrimary
          />

我尝试了很多不同的方法来实现这一点,但每次都失败了!

【问题讨论】:

  • 我想你想为你的组件实现条件渲染。请阅读:reactjs.org/docs/…
  • 感谢杰瑞的回复。我在那里有一个非常简化的组件版本,只是为了理解这一点。我使用样式化组件进行条件渲染。无论如何都想通了!

标签: reactjs react-props


【解决方案1】:

通过提出问题并把它输入出来,我的脑子里就清楚了。真的很简单。提交后我想出了我需要的答案

App.js

 <Modal
        confirmColor={{ solidPrimary: true }}
      />

Modal.js

<button
{...confirmColor}
/>

【讨论】:

  • 太棒了!快乐编码:)
猜你喜欢
  • 2021-11-01
  • 2021-01-27
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 2021-08-29
  • 2018-09-29
  • 1970-01-01
相关资源
最近更新 更多