简体   繁体   English

如何使用 javascript 函数的返回来显示 HTML 按钮?

[英]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:我试图让我的函数返回 HTML 按钮标签,这些标签将显示在页面上,如下所示:

在此处输入图像描述

(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.问题是,正如您所看到的,每一行都有不同的按钮,所以我想做一个函数,将参数作为行的“类别”,例如“游戏”行有 2 个按钮:修改和删除。

Here's my javascript code:这是我的 JavaScript 代码:


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?那么我怎样才能显示这个按钮而不是仅仅将 HTML 标签作为文本呢?

React purposefully makes injecting HTML strings cumbersome to try and steer you towards "thinking in React." React 故意使注入 HTML 字符串变得很麻烦,以尝试引导您“在 React 中思考”。

Here, this means just creating another component that conditionally renders the content you want as JSX .在这里,这意味着只需创建另一个组件,有条件地将您想要的内容呈现为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 prop:

<Category cat="games" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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