我需要一个可重用的组件,在编码时决定任何标记类型,所以硬编码不同的组件将是一个非常复杂的解决方案,所以使用函数的样式处理标记将是非常棒的。
这里是我的沙箱:https://codesandbox.io/s/determined-clarke-gvrzv?fontsize=14
我会根据一个javascript变量动态修改我的html标记,如下所示:
let markup= "li"
function App() {
return (
<div className="App">
<[markup]>Hello World</[markup]>
</div>
);
}
控制台返回给我:
Unexpected token
如何处理这个问题?
谢谢你的任何提示!
发布于 2019-05-28 05:51:26
您可以执行以下操作:
const Markup = "li";
return (
<div className="app">
<Markup>Hello World</Markup>
</div>
)
我不知道你到底想做什么,但你也可以考虑有条件地呈现一个不同的组件:
const temperature = -20;
return (
temperature < 30 ? <Cold /> : <Warm />
);
或者有条件地交换内联标记:
const isCold = temp => temp < 30;
const temperature = -12;
return (
isCold(temperature) ? <div>Brrr!</div> : <span>Sunshine!</span>
);
最后,如果您有许多可能的变体,您可以建立一个getComponent
函数来确定要呈现的内容:
const SeasonalComponents = [
{
handles: temp => temp < 0,
component: () => <div>Brrr!</div>
},
{
handles: temp => temp < 30,
component: () => <div>Get your coat!</div>
},
{
handles: temp => temp < 50,
component: () => <div>Just a jacket</div>
},
{
handles: temp => temp < 100,
component: () => <ImportedSummerComponent />
}
];
function getComponent (temperature) {
const seasonal = SeasonalComponents.find(x => x.handles(temperature);
return seasonal ? seasonal.component : <span>Unseasonable weather!</span>;
}
它允许您的render方法执行查找:
const Component = getComponent(this.props.temp);
return (
<Component />
);
https://stackoverflow.com/questions/56332700
复制相似问题