问题
I have a react app in which I'd like to choose the type of component at runtime. I'm using ES6 and JSX.
Here's my code:
import Canvas from '../components/Canvas'
import CanvasTextbox from '../components/CanvasTextbox';
....
export default class CenterPane extends React.Component {
...
render() {
const canvasKids = [];
//for (var i = 0; i < 1; i++) {
// canvasKids.push(<CanvasTextbox key={i} id={'CanvasTextbox1'} />);
//};
for (var i = 0; i < 1; i++) {
let kid = this.state.kids[i];
let CanvasComp = kid.type; // evaluates to 'CanvasTextbox '
canvasKids.push(<CanvasComp key={i} id={kid.id} />);
console.log(canvasKids)
};
return (
<div>
Canvas:
<Canvas
name="myCanvas"
addChild={this.onAddChild.bind(this)}
>
{canvasKids}
</Canvas>
</div>
);
}
}
When I refer to the component by name, (as in the commented for
loop), it works. However, if I try to use the name from a variable, it doesn't.
I tried assigning the name to a capitalized variable, as guided in the docs, but still nothing.
My canvas component indeed has the child, but it's not a react component, as seen in this react devtools screengrab:
:
The component is not rendered on the canvas at all.
Please help. Thanks
回答1:
Whatever you use as JSX "tag" has to resolve to a function (lowercase names representing HTML tags are the exception). If kid.type
resolves to a string, then it doesn't work.
You'd have to build a name => component
map first:
const components = {
CanvasTextbox,
};
// ...
let CanvasComp = components[kid.type];
回答2:
You cannot use a general expression as the React element type. If you do want to use a general expression to indicate the type of the element, just assign it to a capitalized variable first. This often comes up when you want to render a different component based on a prop:
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} />;
}
To fix this, we will assign the type to a capitalized variable first:
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} />;
}
Please refer the React Documentation for more details.
来源:https://stackoverflow.com/questions/40417644/choosing-react-components-type-at-runtime-in-jsx