Javascript 反应。创建一个返回 html 的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46955880/
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
React. Creating a function that returns html
提问by Kobek
I recently started working with react and I am facing a bit of an issue.
我最近开始使用 react ,但遇到了一些问题。
Currently I have the following piece of code
目前我有以下代码
<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>
)
})
}
This sits in my render()function.
这在我的render()函数中。
However I have this exact same piece of code copy/pasted 5 more times with only minor changes. I wish to extract it to a function, but I am not sure how would I do this.
但是,我将这段完全相同的代码复制/粘贴了 5 次,只做了很小的改动。我希望将它提取到一个函数中,但我不知道该怎么做。
Where should I place the function ? -Inside the render() method?
我应该把函数放在哪里?- 在 render() 方法中?
What should I return from it? - A string that contains the html and variables in {} placeholders?
我应该从中返回什么?- 在 {} 占位符中包含 html 和变量的字符串?
Do I simply call it within the html?
我是否只是在 html 中调用它?
回答by Vivek Doshi
Create function like this :
像这样创建函数:
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>
)
})
}
Use like this :
像这样使用:
<div className="col-md-4"><h4>ML</h4>
{ this.gameLines(game) }
</div>
Dont forget to bind the functions
不要忘记绑定函数
constructor() {
...
this.gameLines = this.gameLines.bind(this);
this.getLineInfo = this.getLineInfo.bind(this);
}

