小编典典

将react组件作为道具传递

reactjs

可以说我有:

import Statement from './Statement';
import SchoolDetails from './SchoolDetails';
import AuthorizedStaff from './AuthorizedStaff';

const MultiTab = () => (
  <Tabs initialIndex={1} justify="start" className="tablisty">
    <Tab title="First Title" className="home">
      <Statement />
    </Tab>
    <Tab title="Second Title" className="check">
      <SchoolDetails />
    </Tab>
    <Tab title="Third Title" className="staff">
      <AuthorizedStaff />
    </Tab>
  </Tabs>
);

在Tabs组件内部,this.props具有属性

+Children[3]
className="tablist"
justify="start"

儿童[0](this.props.children)看起来像

$$typeof:
Symbol(react.element)
_owner:ReactCompositeComponentWrapper
_self:null
_shadowChildren:Object
_source:null
_store:Object
key:null
props:Object
ref:null
type: Tab(props, context)
__proto__
Object

儿童[0]。道具看起来像

+Children (one element)
className="home"
justify="first title"

最终,Children对象看起来像(这是我想要传递的):

$$typeof:Symbol(react.element)
_owner:ReactCompositeComponentWrapper
_self:null
_shadowChildren:undefined
_source:null
_store:
key:null
props:Object
__proto__:Object
**type: function Statement()**
ref:null

问题是这样,如果我这样重写MultiTab

<Tabs initialIndex={1} justify="start" className="tablisty">
  <Tab title="First Title" className="home" pass={Statement} />
  <Tab title="Second Title" className="check" pass={SchoolDetails} />
  <Tab title="Third Title" className="staff" pass={AuthorizedStaff} />
</Tabs>;

在选项卡组件内部

this.props.children 看起来和上面一样。

children[0].props 好像

classname:"home"
**pass: function Statement()**
title: "First title"

我希望该pass物业看起来像。上面只是打印出Statement函数。

$$typeof:Symbol(react.element)
_owner:ReactCompositeComponentWrapper
_self:null
_shadowChildren:undefined
_source:null
_store:
key:null
props:Object
__proto__:Object
**type: function Statement()**
ref:null

这是一个很奇怪的问题,但是长话短说,我正在使用一个库,这就是它的含义。


阅读 230

收藏
2020-07-22

共1个答案

小编典典

使用this.props.children是将实例化组件传递给React组件的惯用方式

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

当直接将组件作为参数传递时,您将其未实例化传递,并通过从props检索它来实例化它。这是一种传递组件类的惯用方式,然后由组件沿树实例化(例如,如果组件在标签上使用自定义样式,但它希望让使用者选择该标签是a
div还是span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

如果您要传递的是类似于孩子的参数作​​为道具,则可以执行以下操作:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

毕竟,React中的属性只是常规的JavaScript对象属性,可以保存任何值-可以是字符串,函数或复杂对象。

2020-07-22