Javascript React / JSX 动态组件名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29875869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:10:35  来源:igfitidea点击:

React / JSX Dynamic Component Name

javascriptreactjsreact-jsx

提问by Sam

I am trying to dynamically render components based on their type.

我正在尝试根据组件的类型动态呈现组件。

For example:

例如:

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

I tried the solution proposed here React/JSX dynamic component names

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

That gave me an error when compiling (using browserify for gulp). It expected XML where I was using an array syntax.

这在编译时给了我一个错误(使用 browserify for gulp)。它期望我在使用数组语法的地方使用 XML。

I could solve this by creating a method for every component:

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

newExampleComponent() {
    return <ExampleComponent />;
}

newComponent(type) {
    return this["new" + type + "Component"]();
}

But that would mean a new method for every component I create. There must be a more elegant solution to this problem.

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

I am very open to suggestions.

我很乐意接受建议。

采纳答案by Alexandre Kirszenberg

<MyComponent />compiles to React.createElement(MyComponent, {}), which expects a string (HTML tag) or a function (ReactClass) as first parameter.

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

You could just store your component class in a variable with a name that starts with an uppercase letter. See HTML tags vs React Components.

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

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

compiles to

编译为

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

回答by gmfvpereira

There is an official documentation about how to handle such situations is available here: https://facebook.github.io/react/docs/jsx-in-depth.html#choosing-the-type-at-runtime

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

Basically it says:

基本上它说:

Wrong:

错误的:

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} />;
}

Correct:

正确的:

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} />;
}

回答by Estus Flask

There should be a container that maps component names to all components that are supposed to be used dynamically. Component classes should be registered in a container because in modular environment there's otherwise no single place where they could be accessed. Component classes cannot be identified by their names without specifying them explicitly because function nameis minified in production.

应该有一个容器将组件名称映射到所有应该动态使用的组件。组件类应该在容器中注册,因为在模块化环境中,否则没有可以访问它们的单一位置。组件类不能在没有明确指定的情况下通过它们的名称来识别,因为功能name在生产中被缩小了。

Component map

组件图

It can be plain object:

它可以是普通对象:

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

Or Mapinstance:

或者Map例如:

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

Plain object is more suitable because it benefits from property shorthand.

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

Barrel module

枪管模块

A barrel modulewith named exports can act as such map:

筒模块与命名出口可以充当这样的地图:

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

This works well with one class per module code style.

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

Decorator

装饰器

Decorators can be used with class components for syntactic sugar, this still requires to specify class names explicitly and register them in a map:

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

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'
  ...
}

A decorator can be used as higher-order component with functional components:

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

const Bar = props => ...;
Bar.displayName = 'Bar';

export default dynamic(Bar);

The use of non-standard displayNameinstead of random property also benefits debugging.

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

回答by Sam

I figured out a new solution. Do note that I am using ES6 modules so I am requiring the class. You could also define a new React class instead.

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

var components = {
    example: React.createFactory( require('./ExampleComponent') )
};

var type = "example";

newComponent() {
    return components[type]({ attribute: "value" });
}

回答by Ray

If your components are global you can simply do:

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

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

回答by Ricardo Pedroni

For a wrapper component, a simple solution would be to just use React.createElementdirectly (using ES6).

对于包装器组件,一个简单的解决方案是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 })
    )
  }
}

回答by Stalinko

Across all options with component maps I haven't found the simplest way to define the map using ES6 short syntax:

在组件映射的所有选项中,我还没有找到使用 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/>
}

回答by Arthur Z.

Having a map doesn't look good at all with a large amount of components. I'm actually surprised that no one has suggested something like this:

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

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

This one has really helped me when I needed to render a pretty large amount of components loaded in a form of json array.

当我需要渲染以 json 数组形式加载的大量组件时,这对我真的很有帮助。

回答by AmerllicA

Assume we have a flag, no different from the stateor props:

假设我们有一个flag,与state或没有什么不同props

import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';

~~~

const Compo = flag ? ComponentOne : ComponentTwo;

~~~

<Compo someProp={someValue} />

With flag Compofill with one of ComponentOneor ComponentTwoand then the Compocan act like a React Component.

使用orCompo之一填充标志,然后可以像 React 组件一样工作。ComponentOneComponentTwoCompo

回答by 1-14x0r

Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.

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

Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:

假设我们要使用这些 url 路径访问具有两个独特视图的页面“snozberrys”:

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

and

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

we define our view's controller like this:

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

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