我正在尝试根据prop值有条件地呈现标签名称。 例子
const SimpleTagName = `Ball${size === 'large' ? 'Large' : 'Small'}`;
return (<SimpleTagName />
但是问题是我渲染了所有小写字母的'balllarge'标签。我在做什么错了?
答案 0 :(得分:0)
尝试使用此方法:
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} />;
}
处理此模式的官方文档参考:https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime
答案 1 :(得分:0)
JSX被转换为一个React.createElement()
调用,因此您有效执行的操作变为:
React.createElement('balllarge')
这不是您想要的。您需要为它传递一个组件而不是字符串,但是仍然可以动态确定,就像这样:
import { BallLarge, BallSmall } from './Balls' // or whatever
const Component = ({ size }) => {
const BallComponent = size === 'large' ? BallLarge : BallSmall
return <BallComponent />
}
(如果您有两个以上的选择,则可能需要不同的方式来处理prop和变量类型之间的映射,但是原理仍然相同:将组件分配给变量,然后在渲染时使用。)