Javascript ReactJS:使用JSX以编程方式更改组件标记
我正在制作一个条件组件,如果定义了href,则返回Javascript ReactJS:使用JSX以编程方式更改组件标记,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我正在制作一个条件组件,如果定义了href,则返回,如果未定义,则返回。我是这样做的: const Label = ({children, ...other}) => { let component; if (other.href) component = <a {...other}> { children } </a> else
,如果未定义,则返回
。我是这样做的:
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
可能吗?像这样的事情
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')
);
const-Label=({children,…other})=>{
let组件;
如果(other.href){
component=如果传递给
值,如component.tag
和JSX transpiler
可以创建动态标记
const Label = ({children, tag, ...other}) => {
const component = { tag: tag };
return (<component.tag {...other}>
{ children }
</component.tag>);
};
您可以尝试Babel replconst标记='p';
Hello;
将文件传输到此var标记='p';
React.createElement(标记,null,'Hello'))
我认为您只需要将jsx标记作为一个变量,不确定它是否需要大写。请注意标记必须大写,因为React interpeter小写为html标记。这是正确的答案。特别是我的第二个示例。
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>);
};