防止TSX/JSX多行HTML输出

huangapple go评论64阅读模式
英文:

Prevent multiline HTML output from TSX/JSX

问题

在一个使用Typescript的React项目中,在组件的渲染中呈现多个变量会导致多行的HTML输出。

这不会导致任何实际问题,视图与预期相符,测试库可以正常使用findByText

当您检查页面时,您会看到:

<p>
    "Foo"
    ": "
    "Bar"
</p>

产生上述示例的代码位于函数组件的返回内部。

const FooBar = ({foo, bar}) => (
    <p>
        {foo}: {bar}
    </p>
);

我希望输出与此一致,将变量连接成一行。输出不被连接的原因是什么?有没有一种方法可以强制将输出合并成一行?

英文:

Within a React project using Typescript, rendering multiple variables within a components render, results in multiline HTML output.

This doesn't cause any real issues, the view is as expected and testing libraries are able to use findByText without an issue.

When you inspect the page, you see:

<p>
    "Foo"
    ": "
    "Bar"
</p>

The code that would produce the above example, is within the return of a functional component.

const FooBar = ({foo, bar}) => (
    <p>
        {foo}: {bar}
    </p>
);

I would expect the output to be consistent with this and concatenate the variables into a single line.

Is there a reason that the output is not concatenated? Is there a way to force a single line output?

答案1

得分: 1

你可以使用模板字符串在生成HTML之前将它们组合在一起。

const FooBar = ({foo, bar}) => (
    <p>
        {`${foo}: ${bar}`}
    </p>
);
英文:

You can use template literals to group them together before HTML is generated.

const FooBar = ({foo, bar}) => (
    <p>
        {`${foo}: ${bar}`}
    </p>
);

huangapple
  • 本文由 发表于 2023年7月10日 19:08:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定