React / JSX 动态组件名称



我正在尝试根据组件的类型动态渲染组件。

例如:

var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />; 
// Returns <examplecomponent />  instead of <ExampleComponent />

我尝试了这里提出的解决方案 反应/JSX 动态组件名称

这在编译时给了我一个错误(使用浏览器进行 gulp)。它期望我使用数组语法的 XML。

我可以通过为每个组件创建一个方法来解决这个问题:

newExampleComponent() {
return <ExampleComponent />;
}
newComponent(type) {
return this["new" + type + "Component"]();
}

但这意味着我创建的每个组件都有一个新方法。这个问题必须有一个更优雅的解决方案。

我非常乐于接受建议。

编辑:正如gmfvpereira这些天所指出的那样,有一个官方文档条目: https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime

<MyComponent />编译为React.createElement(MyComponent, {}),它需要一个字符串(HTML标签)或一个函数(ReactClass)作为第一个参数。

您可以将组件类存储在名称以大写字母开头的变量中。参见 HTML 标签与 React 组件。

var MyComponent = Components[type + "Component"];
return <MyComponent />;

编译为

var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});

有关如何处理此类情况的官方文档可在此处获得:https://facebook.github.io/react/docs/jsx-in-depth.html#choosing-the-type-at-runtime

基本上它说:

错:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// Wrong! JSX type can't be an expression.
return <components[props.storyType] story={props.story} />;
}

正确:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
photo: PhotoStory,
video: VideoStory
};
function Story(props) {
// Correct! JSX type can be a capitalized variable.
const SpecificStory = components[props.storyType];
return <SpecificStory story={props.story} />;
}

应该有一个容器将组件名称映射到应该动态使用的所有组件。组件类应在容器中注册,因为在模块化环境中,没有可以访问它们的单一位置。如果不显式指定组件类,则无法通过其名称来标识组件类,因为函数name在生产中被缩小了。

组件映射

它可以是普通对象:

class Foo extends React.Component { ... }
...
const componentsMap = { Foo, Bar };
...
const componentName = 'Fo' + 'o';
const DynamicComponent = componentsMap[componentName];
<DynamicComponent/>;

或者Map实例:

const componentsMap = new Map([[Foo, Foo], [Bar, Bar]]);
...
const DynamicComponent = componentsMap.get(componentName);

普通对象更合适,因为它受益于属性速记。

桶模块

具有命名导出的桶模块可以充当这样的映射:

// Foo.js
export class Foo extends React.Component { ... }
// dynamic-components.js
export * from './Foo';
export * from './Bar';
// some module that uses dynamic component
import * as componentsMap from './dynamic-components';
const componentName = 'Fo' + 'o';
const DynamicComponent = componentsMap[componentName];
<DynamicComponent/>;

这适用于每种模块代码样式一个类。

装饰

装饰器可以与类组件一起使用以获得语法糖,这仍然需要显式指定类名并将它们注册到映射中:

const componentsMap = {};
function dynamic(Component) {
if (!Component.displayName)
throw new Error('no name');
componentsMap[Component.displayName] = Component;
return Component;
}
...
@dynamic
class Foo extends React.Component {
static displayName = 'Foo'
...
}

装饰器可以用作具有功能组件的高阶组件:

const Bar = props => ...;
Bar.displayName = 'Bar';
export default dynamic(Bar);

使用非标准displayName而不是随机属性也有利于调试。

随着 React.lazy 的引入,我们现在可以使用真正的动态方法来导入组件并渲染它。

import React, { lazy, Suspense } from 'react';
const App = ({ componentName, ...props }) => {
const DynamicComponent = lazy(() => import(`./${componentName}`));

return (
<Suspense fallback={<div>Loading...</div>}>
<DynamicComponent {...props} />
</Suspense>
);
};

当然,这种方法对文件层次结构进行了一些假设,并且会使代码易于破解。

在组件映射的所有选项中,我还没有找到使用 ES6 简短语法定义映射的最简单方法:

import React from 'react'
import { PhotoStory, VideoStory } from './stories'
const components = {
PhotoStory,
VideoStory,
}
function Story(props) {
//given that props.story contains 'PhotoStory' or 'VideoStory'
const SpecificStory = components[props.story]
return <SpecificStory/>
}

我想出了一个新的解决方案。请注意,我使用的是 ES6 模块,所以我需要该类。你也可以定义一个新的 React 类。

var components = {
example: React.createFactory( require('./ExampleComponent') )
};
var type = "example";
newComponent() {
return components[type]({ attribute: "value" });
}

对于包装器组件,一个简单的解决方案是直接使用React.createElement(使用 ES6)。

import RaisedButton from 'mui/RaisedButton'
import FlatButton from 'mui/FlatButton'
import IconButton from 'mui/IconButton'
class Button extends React.Component {
render() {
const { type, ...props } = this.props
let button = null
switch (type) {
case 'flat': button = FlatButton
break
case 'icon': button = IconButton
break
default: button = RaisedButton
break
}
return (
React.createElement(button, { ...props, disableTouchRipple: true, disableFocusRipple: true })
)
}
}

如果您的组件是全局的,您可以简单地执行以下操作:

var nameOfComponent = "SomeComponent";
React.createElement(window[nameOfComponent], {});

拥有大量组件的地图看起来一点也不好。我真的很惊讶没有人提出这样的事情:

var componentName = "StringThatContainsComponentName";
const importedComponentModule = require("path/to/component/" + componentName).default;
return React.createElement(importedComponentModule); 

当我需要渲染以 json 数组形式加载的大量组件时,这个确实帮助了我。

假设我们有一个flag,与stateprops没有什么不同:

import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';
~~~
const Compo = flag ? ComponentOne : ComponentTwo;
~~~
<Compo someProp={someValue} />

使用标志Compo填充ComponentOneComponentTwo之一,然后Compo可以像 React 组件一样运行。

假设您能够从这样的组件中导出 *...

// src/components/index.js
export * from './Home'
export * from './Settings'
export * from './SiteList'

然后,您可以将 * 重新导入到新的 comps 对象中,然后可以使用该对象访问模块。

// src/components/DynamicLoader.js
import React from 'react'
import * as comps from 'components'
export default function ({component, defaultProps}) {
const DynamicComponent = comps[component]
return <DynamicComponent {...defaultProps} />
}

只需传入一个字符串值,该值标识要绘制的组件,无论需要在哪里绘制它。

<DynamicLoader component='Home' defaultProps={someProps} />

我们希望通过动态组件加载访问各种视图。下面的代码提供了一个工作示例,说明如何使用从 url 的搜索字符串分析的字符串来实现此目的。

假设我们想使用这些 url 路径访问具有两个唯一视图的页面"snozberrys":

'http://localhost:3000/snozberrys?aComponent'

'http://localhost:3000/snozberrys?bComponent'

我们像这样定义视图的控制器:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';
const views = {
aComponent: <AComponent />,
console: <BComponent />
}
const View = (props) => {
let name = props.location.search.substr(1);
let view = views[name];
if(view == null) throw "View '" + name + "' is undefined";
return view;
}
class ViewManager extends Component {
render() {
return (
<Router>
<div>
<Route path='/' component={View}/>
</div>
</Router>
);
}
}
export default ViewManager
ReactDOM.render(<ViewManager />, document.getElementById('root'));

👍 您可以使用回退组件创建可重用组件

export const StringComponent = (Base, { name, Fallback = undefined, ...rest }) => {
const Component = Base[name];
// return fallback if the component doesn't exist
if (!Component) return <Fallback/>
return <Component {...rest}/>;
};

并像这样称呼它:

import * as Pages from "../pages"
const routes = [
{path: "/", element: "Home" },
{path: "/about", element: "About" },
{path: "*", element: "NotFound" },
]
export function App(){

const Fallback = Pages.NotFound
// render each route using a string as name
return (
<div>
{ 
routes.map(page => 
StringComponent(Pages, { name: page.element, Fallback }) 
)
}
</div>
)
}

OBS:导入的页面需要像这样:

import Home from "./home"
import About from "./about"
import NotFound from "./not-found"
export { Home, About, NotFound }

比如说,你的组件是用Components.js定义的:

import React from 'react';
class Foo extends React.Component {
render () {
return (
<div>
<p>Foo is best</p>
</div>
);
}
}
class Bar extends React.Component {
render () {
return (
<div>
<p>Bar is Bar</p>
</div>
);
}
}
export {
Foo,
Bar
};

您可以import * as X from Y,所有组件类都将放入字典 X 中。然后以这种方式从字符串中渲染它们:

import React from 'react';

import * as componentClasses from './Components';
class App extends React.Component {
render () {
const componentClass = componentClasses['Foo']; /** 'Foo' or 'Bar' **/
const component = React.createElement(componentClass, {});
return (
<div>
<h1>Cool</h1>
{component}
</div>
);
}
}
export default App;

https://codesandbox.io/s/unruffled-maria-i8psmo?file=/src/App.js

我使用了一点不同的方法,因为我们总是知道我们的实际组件,所以我想应用开关大小写。 在我的情况下,组件总数也约为 7-8。

getSubComponent(name) {
let customProps = {
"prop1" :"",
"prop2":"",
"prop3":"",
"prop4":""
}
switch (name) {
case "Component1": return <Component1 {...this.props} {...customProps} />
case "Component2": return <Component2 {...this.props} {...customProps} />
case "component3": return <component3 {...this.props} {...customProps} />
}
}

编辑:其他答案更好,请参阅评论。

我以这种方式解决了同样的问题:

...
render : function () {
var componentToRender = 'component1Name';
var componentLookup = {
component1Name : (<Component1 />),
component2Name : (<Component2 />),
...
};
return (<div>
{componentLookup[componentToRender]}
</div>);
}
...

最新更新