React. Creating a function that returns html(做出反应.创建一个返回 html 的函数)
问题描述
我最近开始使用 react,但遇到了一些问题.
I recently started working with react and I am facing a bit of an issue.
目前我有以下代码
<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() 函数中.
This sits in my render() function.
但是,我将这段完全相同的代码复制/粘贴了 5 次以上,只进行了微小的更改.我希望将其提取到一个函数中,但我不知道该怎么做.
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.
我应该把函数放在哪里?- 在 render() 方法里面?
Where should I place the function ? -Inside the render() method?
我应该从中返回什么?- 在 {} 占位符中包含 html 和变量的字符串?
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?
推荐答案
像这样创建函数:
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);
}
                        这篇关于做出反应.创建一个返回 html 的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:做出反应.创建一个返回 html 的函数
				
        
 
            
        - addEventListener 在 IE 11 中不起作用 2022-01-01
 - Flexslider 箭头未正确显示 2022-01-01
 - 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
 - 失败的 Canvas 360 jquery 插件 2022-01-01
 - 400或500级别的HTTP响应 2022-01-01
 - CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
 - Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
 - Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
 - Fetch API 如何获取响应体? 2022-01-01
 
						
						
						
						
						