react。创建一个返回 html 的函数

IT技术 javascript html function reactjs return
2021-04-07 19:45:57

我最近开始使用 react ,但遇到了一些问题。

目前我有以下代码

<div className="col-md-4"><h4>ML</h4>
{
    game.lines.map(function (lineGroup) {
        return (
            <div className="row">
                <div className="col-md-1">
                    {lineGroup.Pay}
                </div>
                <div className="col-md-3">
                    <strong>{getLineInfo(lineGroup.HomeInfo)}</strong>
                </div>
                <div className="col-md-3">
                    <strong>{getLineInfo(lineGroup.Score)}</strong>
                </div>
                <div className="col-md-3">
                    <strong>{getLineInfo(lineGroup.AwayInfo)}</strong>
                </div>
            </div>
        )
    })
}

这在我的render()功能中。

但是,我将这段完全相同的代码复制/粘贴了 5 次,仅进行了很小的更改。我希望将它提取到一个函数中,但我不知道该怎么做。

我应该把函数放在哪里?- 在 render() 方法中?

我应该从中返回什么?- 在 {} 占位符中包含 html 和变量的字符串?

我是否只是在 html 中调用它?

1个回答

创建这样的函数:

function gameLines(game) {
    return game.lines.map(function (lineGroup) {
        return (
            <div className="row">
                <div className="col-md-1">
                    {lineGroup.Pay}
                </div>
                <div className="col-md-3">
                    <strong>{this.getLineInfo(lineGroup.HomeInfo)}</strong>
                </div>
                <div className="col-md-3">
                    <strong>{this.getLineInfo(lineGroup.Score)}</strong>
                </div>
                <div className="col-md-3">
                    <strong>{this.getLineInfo(lineGroup.AwayInfo)}</strong>
                </div>
            </div>
        )
    })
}

像这样使用:

<div className="col-md-4"><h4>ML</h4>
    { this.gameLines(game) }
</div>

不要忘记绑定函数

constructor() {
    ...
    this.gameLines = this.gameLines.bind(this);
    this.getLineInfo = this.getLineInfo.bind(this);
}
如何从 JavaScript 函数返回 HTML 代码?这个问题在 2017 年在其他地方被问过,目前还没有答案。有谁明白这一点吗?
2021-05-26 19:45:57
它显然是一种名为 JSX 的新语言:reactjs.org/docs/introducing-jsx.html我想它只适用于反应。
2021-06-09 19:45:57