简体   繁体   English

React.js 在迭代时将列表项传递给数据库

[英]React.js passing an list item to Database while in iteration

I have a list of items and want to iterate over them, create a div block with a button and if the user clicks on the button send this data to a function and then database.我有一个项目列表,想要遍历它们,创建一个带有按钮的 div 块,如果用户单击该按钮,则将此数据发送到 function,然后发送到数据库。 However with my code, instead of the item data, I only send undefined.但是,使用我的代码,而不是项目数据,我只发送未定义的。

import React, {useState, useEffect} from 'react';
import './App.css';
import allItemsList from './allItemsList.json'

function App() {
  const itemsList = allItemsList[0].itemslist
  
  function addDemoButton (currentItem) {

    ///how do i pass the currentItem variable here to this function?

  }

  
  return (
    <div className="App">
      <div className="itembox">
      {itemsList.map((currentItem ) => (
                <div >
                  <h6>{`${currentItem}` }</h6>
                  <p>some information here</p>
                  <button onClick={(currentItem) => addDemoButton()}>Free Demo</button>
                </div>
            ))}
      </div>
    </div>
  );
}


this is the allitemslist.json that i import as allItemsList:这是我作为 allItemsList 导入的 allitemslist.json:


[
  {
    "itemslist": ["item1", "item2", "item3"]
  }
]


Just add it in addDemoButton as parameter of method只需将其添加到addDemoButton作为方法的参数

return (
    <div className="App">
      <div className="itembox">
      {itemsList.map((currentItem ) => (
                <div >
                  <h6>{`${currentItem}` }</h6>
                  <p>some information here</p>
                  <button onClick={() => addDemoButton(currentItem)}>Free Demo</button>
                </div>
            ))}
      </div>
    </div>
  );

In your code,在您的代码中,

addDemoButton()

is empty without any parameter.是空的,没有任何参数。

I believe you should put currentItem inside the function and called it.我相信您应该将 currentItem 放入 function 并调用它。

addDemoButton(currentItem);

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

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