反应长按错误:无法读取未定义的接头属性

时间:2019-11-03 09:43:25

标签: javascript reactjs

我还是React / JS的新手,目前正在移动网站上工作,想实现不带按钮的删除。为此,我使用了一个长按事件,该事件允许用户长按一个输入字段,然后在满足时间要求后将其删除。

我想我应该做的就是像这样拼接输入字段:

  handleButtonPress() {
    this.buttonPressTimer = setTimeout(() => this.inputs.splice(index, 1), 950);
  }

长按事件功能起作用,只是网站在遇到时间事件后收到错误消息:

TypeError: Cannot read property 'splice' of undefined

 | }
  52 | 
  53 | handleButtonPress() {
> 54 |   this.buttonPressTimer = setTimeout(() => this.inputs.splice(index, 1), 950);
     | ^  55 | }
  56 | 
  57 | handleButtonRelease() {

我尝试使用此功能,但收到相同的错误:

  handleButtonPress() {

    const newInput = this.state.inputs
    this.buttonPressTimer = setTimeout(() => newInput.inputs.splice(index, 1), 950);
  }

这是我完全尝试实现此功能的方式:

Edit.jsx

import React from 'react'


export default class Edit extends React.Component {
  constructor(props) {
    super(props)
    this.handleButtonPress = this.handleButtonPress.bind(this)
    this.handleButtonRelease = this.handleButtonRelease.bind(this)

    this.state = { inputs: [], text: ''}

    this.onDragEnd = this.onDragEnd.bind(this);
  }

  handleButtonPress() {
    this.buttonPressTimer = setTimeout(() => this.inputs.splice(index, 1), 950);
  }

  handleButtonRelease() {
    clearTimeout(this.buttonPressTimer);
  }
    this.setState({ input })}

  render() {
      return (
        <>
            <div
              onTouchStart={this.handleButtonPress}
              onTouchEnd={this.handleButtonRelease}
              onMouseDown={this.handleButtonPress}
              onMouseUp={this.handleButtonRelease}
              onMouseLeave={this.handleButtonRelease}>

             //removed map function of inputs    

            </div>
        </>
      )
    }
  }
}

我在这里删除了大多数代码,因为它与问题无关。请注意,此示例中未包含用于输入的.map函数。我不确定该问题该如何继续发展。

1 个答案:

答案 0 :(得分:0)

您必须始终使用对象键。给定构造函数:

this.state = { inputs: [], text: ''}

仅定义this.state.inputs,未定义this.inputs,类似于以下代码中的this.state.inputs.inputs

const newInput = this.state.inputs
...newInput.inputs