Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ReactJS:使用JSX以编程方式更改组件标记_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript ReactJS:使用JSX以编程方式更改组件标记

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

我正在制作一个条件组件,如果定义了href,则返回
,如果未定义,则返回
。我是这样做的:

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 repl
const标记='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>);
};