我需要一个可重用的组件,其任何标记类型都在编码时在内部决定,因此对不同的组件进行硬编码将是一个非常复杂的解决方案,因此使用函数的样式处理标记将非常棒。
这是我的沙箱: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
如何处理这个问题?
感谢您的任何提示!
最佳答案
你可以这样做:
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>;
}
它允许你的渲染方法进行查找:
const Component = getComponent(this.props.temp);
return (
<Component />
);
关于javascript - ReactJS - 如何动态更改 html 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332700/