Reactコンポーネントをpropsとして渡す 質問する

Reactコンポーネントをpropsとして渡す 質問する

たとえば、次のようなものがあるとします。

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>
);

タブコンポーネント内には、this.propsプロパティがあります

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

Children[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

Children[0].propsは次のようになります

+Children (one element)
className="home"
title="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

これは奇妙な質問ですが、長い話になりますが、私はライブラリを使用しており、結局のところ、これがその通りです。

ベストアンサー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 から取得してインスタンス化します。これは、ツリーの下位のコンポーネントによってインスタンス化されるコンポーネント クラスを渡す慣用的な方法です (たとえば、コンポーネントがタグにカスタム スタイルを使用するが、そのタグが か かを選択できるようにする場合など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 オブジェクト プロパティであり、文字列、関数、複雑なオブジェクトなど、任意の値を保持できます。

おすすめ記事