【问题标题】:React JS event.target.value sometimes null sometimes what it needs to beReact JS event.target.value 有时为 null 有时它需要是什么
【发布时间】:2020-07-25 17:21:27
【问题描述】:

我有一个表格,其中的行从数组映射,每行都有一个编辑按钮。我使用 map(value, index) 为每个按钮指定了一个值。

var selected;

 handleUpdate = (e) => {
    e.persist();
    selected = filteredresults[e.target.value];
    this.setState({
      updateform: true,
      viewuser: false,
    });
  };

 <Button
   type="button"
   color="primary"
   value={index}
   onClick={(e) => this.handleUpdate(e)}   Or   onClick={this.handleUpdate}
   style={{ width: "5px" }}>
   <EditIcon />
 </Button>

当我点击按钮时,e.target.value 有时为空或未定义,有时为索引值。

我读到了 react 中的事件池,所以我添加了 e.persist(),但随机行为仍然存在。

为什么是“有时”?预期的行为每次都应该是相同的。

【问题讨论】:

  • 尝试注释掉e.persist,看看会发生什么。
  • 我添加了 e.persist 因为它并非每次都有效。有时有时不是。

标签: reactjs button onclick


【解决方案1】:
    try passing the value of index directly as a parameter to handleUpdate method as shown below. 
Also, you can remove the e.persist() call. That's irrelevant.
    handleUpdate = (e,value) => {
        selected = filteredresults[value];
        this.setState({
          updateform: true,
          viewuser: false,
        });
      };
    
     <Button
       type="button"
       color="primary"
       onClick={(e) => this.handleUpdate(e,index)} 
       style={{ width: "5px" }}>
       <EditIcon />
     </Button>

【讨论】:

  • 嘿,这个解决方案有效,我的错,这太简单了。但我仍然对它的随机行为感到好奇。
猜你喜欢
  • 2021-11-06
  • 2020-03-31
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 2022-11-11
相关资源
最近更新 更多