【问题标题】:onDoubleClick is not working on react to call a functiononDoubleClick 无法响应调用函数
【发布时间】:2022-08-16 23:29:57
【问题描述】:

我在这里关注这个 React 教程:https://ibaslogic.com/how-to-edit-todos-items-in-react/ 来构建一个简单的 TO DO 应用程序。

我还查看了Why onDoubleClick event is not working in React.js?,但在我的示例中没有需要担心的onclick 事件。

我的onDoubleClick 事件应该调用一个函数handleEditing,但是当我双击一个列表项时没有任何反应。

我不确定为什么它不起作用(网络浏览器似乎没有注册双击事件。

下面是我的例子:

import React from \"react\";
import styles from \"./TodoItem.module.css\";

class TodoItem extends React.Component {
  state = {
    editing: false,
  };

  handleEditing = () => {
      console.log(\"doubleClick\")
    this.setState({
      editing: true,
    });
  };

  render() {

    const completedStyle = {
      fontStyle: \"italic\",
      color: \"#595959\",
      opacity: 0.4,
      textDecoration: \"line-through\",
    };
    
    const { completed, id, title } = this.props.todo;
    
    let viewMode = {}
let editMode = {}

if (this.state.editing) {
  viewMode.display = \"none\"
} else {
  editMode.display = \"none\"
}
    
    return (
      <li className={styles.item}>
        <div onDoubleClick={this.handleEditing} style={viewMode}>
          <input
            type=\"checkbox\"
            className={styles.checkbox}
            checked={completed}
            onChange={() => this.props.handleChangeProps(id)}
          />
          <button onClick={() => this.props.deleteTodoProps(id)}>Delete</button>
          <span style={completed ? completedStyle : null}>{title}</span>
        
        </div>
        <input type=\"text\" style={editMode} className={styles.textInput} />
      </li>
    );
  }
}

export default TodoItem;

我不认为这是相关的,但这是我的 css:

.item {
    font-size: 1.2rem;
    list-style-type: none;
    padding: 17px 0px;
    border-bottom: 1px solid #eaeaea;
  }
  
  .checkbox {
    margin-right: 15px;
  }
  
  .item button {
    font-size: 13px;
    background: #f1f3f4;
    border: none;
    cursor: pointer;
    float: right;
    outline: none;
    border-radius: 100px;
    height: 50px;
    width: 50px;
    margin: -10px 0 0 10px;
  }


  .textInput {
    width: 100%;
    padding: 10px;
    border: 1px solid #dfdfdf;
  }
  • 我无法重现该错误。你能把你的代码贴在codesandbox上然后贴在这里吗?

标签: javascript reactjs ondoubleclick


【解决方案1】:

更新的答案:

正如在 cmets 中发现的那样,问题是操作系统和浏览器的组合。本例中的 Windows / Chrome。

老答案:

我没有详细阅读,但我能发现的第一个区别是,在您的代码中,handleEditing 未绑定。这不应该阻止你的 console.log 的输出。出现了吗?

onDoubleClick={this.handleEditing.bind(this)}

希望这对您的情况有所帮助。

【讨论】:

  • 感谢您的回复@csenk - 不幸的是,它似乎没有帮助,因为没有调用该函数
  • 嘿@KatieMelosto,没问题。我很快就尝试了您的代码:codesandbox.io/s/suspicious-dewdney-lfct8?file=/src/App.js,它似乎对我有用。在 Mac 上的 Chrome 中使用它。
  • handleEditing是一个箭头函数,所以你不需要绑定this
  • 确实 :) 细节很重要 :D
  • 嗨@csenk ...我实际上切换到Windows上的Internet Explorer,它现在可以工作了!
【解决方案2】:

onDoubleClick 在您的开发工具未打开时有效

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多