我试图根据组件的类型动态呈现组件。
例如:
var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />;
// Returns <examplecomponent /> instead of <ExampleComponent />
我尝试了这里提出的React/JSX动态组件名称的解决方案
这在编译时给了我一个错误(使用browserify for 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
关于如何处理这种情况的官方文档可以在这里找到: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} />;
}
<MyComponent />编译为React。createElement(MyComponent,{}),它需要一个字符串(HTML标签)或一个函数(ReactClass)作为第一个参数。
您可以将组件类存储在一个名称以大写字母开头的变量中。参见HTML标签vs React组件。
var MyComponent = Components[type + "Component"];
return <MyComponent />;
编译,
var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
对于包装器组件,一个简单的解决方案就是使用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 })
)
}
}
随着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>
);
};
当然,这种方法对文件层次结构做了一些假设,并且可以使代码很容易被破坏。