【问题标题】:Pass prop from intermediate component into props.children将 prop 从中间组件传递到 props.children
【发布时间】:2021-11-23 19:54:13
【问题描述】:

我想制作一个功能组件,为其直接子级提供道具。我不想使用上下文,因为我希望它只对直系子女可用。

所以给定以下组件:

const TopLevel = () => {
  return (
    <FooGiver>
      <LowerLevel />
    </FooGiver>
  )
}

interface LowerLevelProps {
  foo?: string;
}
const LowerLevel = ({foo}: LowerLevelProps) => {
  return foo ? <p>{foo}</p> : <p>No foo provided</p> 
}

const FooGiver = ({ children }: FooGiverProps) => {
  const foo = bar // TODO: This should set its children's `foo` prop to "bar"
 
  return (
    <>
      { children }
    </>
  )
}

是否可以定义FooGiver,这样它就会给它收到foo 属性"bar" 的任何孩子?

如果是这样,我是否需要继续保持 foo 属性可选,或者 TS 会选择 FooGiver 将始终设置 foo,并且不会抱怨我在没有提供所需 @ 的情况下调用了 &lt;LowerLevel /&gt; 987654329@道具?

【问题讨论】:

  • 你在孩子身上试过.prop吗?

标签: javascript reactjs typescript


【解决方案1】:

我认为这样做可以为所有孩子添加道具

以下示例组件将一个名为 newProp 的新道具添加到它所接收的所有子级中,值为 true

function Parent({children}){
    return <>

        {children.map(child=>{
            const modified = child;
            modified.props["newProp"] = true;//add new value to prop
            return modified
        })}

    </>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2021-10-15
    • 2020-08-05
    • 2020-05-22
    相关资源
    最近更新 更多