React / JSX动态组件名称问题如何解决?
- 回答 (2)
- 关注 (0)
- 查看 (598)
我正在尝试根据其类型动态呈现组件。
例如:
var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />;
// Returns <examplecomponent /> instead of <ExampleComponent />
这在编译时给我一个错误(使用browserify for gulp)。它期望XML在我使用数组语法的地方。
我可以通过为每个组件创建一个方法来解决这个问题:
newExampleComponent() {
return <ExampleComponent />;
}
newComponent(type) {
return this["new" + type + "Component"]();
}
但是这意味着我创建的每个组件都有一个新的方法。这个问题必须有一个更优雅的解决方案。
我非常乐于接受建议。
<MyComponent />编译为React.createElement(MyComponent, {}),它需要一个字符串(HTML标记)或一个函数(ReactClass)作为第一个参数。
可以将组件类存储在名称以大写字母开头的变量中。查看HTML标记与React组件。
var MyComponent = Components[type + "Component"];
return <MyComponent />;
编译
var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
赞0收藏0评论0分享
有关于如何处理此类情况的官方文档可在此处获得: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} />;
}
赞1收藏1评论0分享
11.11 智慧上云
云服务器企业新用户优先购,享双11同等价格