javascript 相邻的 JSX 元素必须包含在带有换行标记的封闭标记中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32617685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:31:27  来源:igfitidea点击:

Adjacent JSX elements must be wrapped in an enclosing tag with line break tag

javascripthtmlbackbone.jsreactjs

提问by chris

Imagine:

想象:

return (<a href="{this.props.url}">{this.props.name}</a><br>)

also attempted with

也尝试过

return (<a href="{this.props.url}">{this.props.name}</a><br />)

While the script does run without issue, the JSX compiler is upset by the <br>tag, since its a lone wolf in the logic and has no open/close tag it just is.

虽然脚本确实运行没有问题,但 JSX 编译器对<br>标签感到不安,因为它在逻辑中是一只孤狼,并且没有打开/关闭标签。

if on the other hand I remove the <br>

如果另一方面我删除 <br>

return (<a href="{this.props.url}">{this.props.name}</a>)

there is no error thrown, pretty self explanatory as far as what the issue is. The question however is how to resolve the underlying problem. how can I have that tag (or its equivalent if need be). Be added after every one of the above rendering statements.

没有抛出错误,就问题所在而言非常不言自明。然而,问题是如何解决根本问题。我怎么能有那个标签(或者它的等效物,如果需要的话)。在上述每一条渲染语句之后添加。

Things to assume, this is a loop of urls/names that generate an html list of links on the page. Everything minus this factor thus far works.

要假设的事情,这是一个 urls/names 循环,它在页面上生成一个 html 链接列表。到目前为止,一切减去这个因素都有效。

The underlying issue overall is a issue of aesthetics. I am using bootstrap, and in that things are fairly uniform and I have no desire to create one-off classes or inline styles to accommodate the line-break. This is just purely for the sake of maintainability down the road.

总体而言,根本问题是美学问题。我正在使用引导程序,因此事情相当统一,我不想创建一次性类或内联样式来适应换行符。这纯粹是为了以后的可维护性。

回答by Eelke

You need a wrapping root tag:

你需要一个包装根标签:

<div>
    <a href={this.props.url}>{this.props.name}</a>
    </br>
</div>

回答by Caio Saldanha

You can render many 'tags' with a Component, but it MUST be within a 'parent tag', just like Eelke said.

你可以用一个组件渲染许多“标签”,但它必须在一个“父标签”内,就像 Eelke 所说的那样。

Another way to do so is to declare a variable within render() function and return it:

另一种方法是在 render() 函数中声明一个变量并返回它:

render(){
    var step;
    if(this.props.gender==="male"){
        step = (
          <div>
            <p>A pessoa chamada {this.props.name} eh um homem! </p>
            <b>aqui</b>
          </div>
        );
    }else{
        step = (
          <div>
            <p>A pessoa chamada {this.props.name} eh uma mulher! </p>
            <b>aqui</b>
          </div>
        );
    }
    return step;
}