简体   繁体   English

将功能组件 props 传递给 React 中的静态属性

[英]Passing functional component props to a static property in React

Say, I have a functional React component:说,我有一个功能性的 React 组件:

const MyComponent = props => {...}

and I set a static property on it:我在它上面设置了一个静态属性:

MyComponent.layout = MyLayoutComponent

Is there a way to pass/access the props from MyComponent to/in MyLayoutComponent ?有没有办法将propsMyComponent传递/访问到/在MyLayoutComponent

I think you can with something like this我想你可以用这样的东西

const Bar = (props: any) => {
  console.log('bar props: ', props)
  // {foo: "FOO" ...}
  return <div>bar</div>
}

Bar.displayName = 'Bar'

const Foo = (props: any) => {
  return (
    <div>
      {React.Children.map(props.children, (child: any) => {
        console.log('name: ', child.type?.displayName)
        return React.cloneElement(child, props)
      })}
    </div>
  )
}

Foo.layout = Bar

... ...

  <Foo foo="FOO">
    <Foo.layout />
  </Foo>

React children api反应儿童api

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM