[英]ReactJS: programmatically change component tag with JSX
我正在制作一個條件組件,如果定義了href則返回<a>
,如果沒有定義則返回<div>
。 我這樣做:
const Label = ({children, ...other}) => {
let component;
if (other.href)
component =
<a {...other}>
{ children }
</a>
else
component =
<div {...other}>
{ children }
</div>
return component;
}
export default Label
有沒有辦法只通過更改標簽名稱來制作這個組件? 我知道如果我使用手動方式創建組件 ( React.createElement
) 我可以通過更改傳遞的第一個參數來做到這一點,因為它是一個字符串。 但是對於 JSX,它有點不同。 我雖然有點像
let component =
<{tag} {...other}>
{ children }
</{tag}>
可能嗎?
是這樣的嗎?
const Label = ({children, ...other}) => {
let component;
if (other.href) {
component = <a {...other}>{ children }</a>;
} else if (other.tag) {
const Tag = other.tag;
component = <Tag {...other}>{ children }</Tag>;
} else {
component = <div {...other}>{ children }</div>;
}
return component;
}
ReactDOM.render(
<Label href="#">Hello World</Label>,
document.getElementById('root')
);
ReactDOM.render(
<Label>Not a Link</Label>,
document.getElementById('rootTwo')
);
ReactDOM.render(
<Label tag="p">Paragraph</Label>,
document.getElementById('rootThree')
);
工作演示: , https ://jsfiddle.net/tgm4htac/
如果你傳遞給<>
值,比如component.tag
和JSX transpiler
可以創建動態標簽。
const Label = ({children, tag, ...other}) => {
const component = { tag: tag };
return (<component.tag {...other}>
{ children }
</component.tag>);
};
要么
const Label = ({children, tag, ...other}) => {
const Component = tag;
return (<Component {...other}>
{ children }
</Component>);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.