繁体   English   中英

如何从 html 中将 arguments 传递给 function?

[英]How can I pass in the arguments to a function in react from within the html?

我正在遍历对象数组,我想为每个迭代调用 function,对象属性为 arguments。 当我单击按钮时,它所做的只是重新加载页面并且不会将 arguments 传递给 function,因为当我 console.log() 时我在控制台中看不到它

const Posts = () => {


  const mySubmitHandler = async ( pos) => {
    console.log(pos);
    try {
      console.log(window.web3.currentProvider)
      console.log(accounts)
      const res = await snInstance.reply(pos, reply, { from: accounts[0] });
      console.log("-----------------rererer-----------------")
      console.log(res, accounts);
    } catch (e) {
      console.error(e)
    }
  }

 return (
      <div>
        {socialNetworkContract.posts.map((p, index) => {
          return <tr key={index}>
    <form onSubmit={() => mySubmitHandler(p.postsCounter)} style={{ textAlign: 'center' }}>

          <div style={{ padding: '10px' }} >
            <input
              type='text'
              name='reply'
              onChange={myChangeHandler}
              required
            /></div>

    <input type='submit' value="Reply" />
    </form>
    
     <button variant="primary" onClick={Like}>Like</button>
     </div>
  )
}


export default Posts;

当我在 snInstance.reply() 中替换“pos”时,function 将起作用,但它只发布对索引 1 帖子的回复。p.publisher 是 integer,p.postCounter 也是如此。 我需要将这些作为 arguments 传递给这些函数。

async请求的情况下防止默认页面重新加载:

将事件 object e传递给onSubmit()处理程序:

onSubmit={(e) => mySubmitHandler(e, p.postsCounter)}

然后,在onSubmit()内部,使用e.preventDefault()

const mySubmitHandler = async (e, pos) => {
    .....
}

您必须使用event.preventDefault() 停止表单提交的默认操作;

<form onSubmit={(event)=>{
 event.preventDefault();
 mySubmitHandler(p.postsCounter);
}}
...>

暂无
暂无

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

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