コンポーネントをそのタイプに基づいて動的にレンダリングしようとしています。
例えば:
var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />;
// Returns <examplecomponent /> instead of <ExampleComponent />
ここで提案された解決策を試してみましたReact/JSX 動的コンポーネント名
コンパイル時にエラーが発生しました (gulp に browserify を使用)。配列構文を使用している箇所で XML が想定されていました。
すべてのコンポーネントに対してメソッドを作成することで、この問題を解決できます。
newExampleComponent() {
return <ExampleComponent />;
}
newComponent(type) {
return this["new" + type + "Component"]();
}
しかし、それは作成するコンポーネントごとに新しいメソッドが必要になることを意味します。この問題には、もっとエレガントな解決策があるはずです。
私は提案を非常に歓迎します。
編集:指摘されたようにgmfvペレイラ最近、これに関する公式ドキュメントエントリがあります:https://reactjs.org/docs/jsx-in-depth.html#実行時に型を選択する
ベストアンサー1
<MyComponent />
は にコンパイルされReact.createElement(MyComponent, {})
、最初のパラメータとして文字列 (HTML タグ) または関数 (ReactClass) が想定されます。
コンポーネントクラスを大文字で始まる名前の変数に保存することもできます。HTML タグと React コンポーネント。
var MyComponent = Components[type + "Component"];
return <MyComponent />;
コンパイルすると
var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});