简体   繁体   中英

How can I display an HTML button using the return from a javascript function?

I trying to have my function return HTML button tags that will be displayed on the page like so:

在此处输入图像描述

(without the hover thing)

The problem is that as you can see every row has different buttons, so I wanted to make a function that takes in the parameter the "category" of the row, for example the "Games" row has 2 buttons: Modify and Delete.

Here's my javascript code:


function Category(cat) {
    if (cat == "games") {
        let innerhtml = `<div className='game_buttons'> <button className='modify'>Modify</button> <button className='delete'>Delete</button> </div>`
        return innerhtml
    }


    if (cat == "upcoming") {
        let innerhtml = `<div className='game_buttons'>  <button className='released'>Released</button> <button className='modify'>Modify</button> <button className='delete'>Delete</button> </div>`
        return innerhtml
    }


    if (cat == "featured") {
        let innerhtml = `<div className='game_buttons'> <button className='delete'>Delete</button> </div>`
        return innerhtml
    }
}


I placed that same function where I need it to be displayed, like so :


                    <div className='game_buttons'>
                        {Category("games")}
                    </div>

But I get this : 在此处输入图像描述

So how could I display this buttons instead of just getting the HTML tags as text?

React purposefully makes injecting HTML strings cumbersome to try and steer you towards "thinking in React."

Here, this means just creating another component that conditionally renders the content you want as JSX .

function Category(props) {
    if (props.cat === "games") {
        return (
            <div className="game_buttons">
                <button className="modify">Modify</button>
                <button className="delete">Delete</button>
            </div>
        );
    }

    if (props.cat === "upcoming") {
        return (
            <div className="game_buttons">
                <button className="released">Released</button>
                <button className="modify">Modify</button>
                <button className="delete">Delete</button>
            </div>
        );
    }

    if (props.cat === "featured") {
        return (
            <div className="game_buttons">
                <button className="delete">Delete</button>
            </div>
        );
    }
}

Then, render Category and pass in your cat prop:

<Category cat="games" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM