Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - React. Creating a function that returns html

I recently started working with react and I am facing a bit of an issue.

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.

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.

Where should I place the function ? -Inside the render() method?

What should I return from it? - A string that contains the html and variables in {} placeholders?

Do I simply call it within the html?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...