【问题标题】:Select JavaScript object from onClick event从 onClick 事件中选择 JavaScript 对象
【发布时间】:2020-04-05 09:49:49
【问题描述】:

我有一个包含两个数组的父组件

newChoiceArray: [
    { id: 1, text: '1', questionId: 'favourite number?', value: '1' },
    { id: 2, text: '2', questionId: 'favourite number?', value: '2' },
    { id: 3, text: '3', questionId: 'favourite number?', value: '3' },
  ],
  ChoiceArray: [
    { id: 4, text: 'red', questionId: 'favourite colour?', value: '1' },
    { id: 5, text: 'blue', questionId: 'favourite colour?', value: '4' },
  ],
}

我有一个组件,它为数组中的每个对象呈现一个按钮

const MultiChoiceQuestions = props => {
  const { multiChoiceArray, handleClick } = props
  return (
    <div>
      {multiChoiceArray.map(questionChoice => {
        return (
          <button type="button" key={questionChoice.id} onClick={handleClick}>
            {questionChoice.text}
          </button>
        )
      })}
    </div>
  )
}

当我渲染我的子组件时,我可以传递一个数组作为道具

<MultiChoiceQuestions handleClick={this.testClick} multiChoiceArray={newChoiceArray} />
<MultiChoiceQuestions handleClick={this.testClick} multiChoiceArray={ChoiceArray} />

当我单击按钮时,我想查看该数组中的哪个对象被选中。

    testClick = event => {
      event.preventDefault()
      console.log(event.currentTarget)
  }

而不是输出这个&lt;button type="button"&gt;3&lt;/button&gt; 它应该输出这个{ id: 3, text: '3', questionId: 'favourite number?', value: '3' },

【问题讨论】:

    标签: javascript reactjs oop ecmascript-6 jsx


    【解决方案1】:

    您可以将对象作为按钮值传递,例如:

    {multiChoiceArray.map(questionChoice => {
      return (
        <button type="button" key={questionChoice.id} value={JSON.stringify(questionChoice)} onClick={handleClick}>
          {questionChoice.text}
        </button>
      )
    }
    

    然后您可以使用 currentTarget 中的属性 value 来捕捉它:

     testClick = event => {
       event.preventDefault()
       console.log(JSON.parse(event.currentTarget.value))
    }
    

    我不知道是否是最好的方法,但我知道这很有效。

    更新

    我想知道这个问题,你会使用事件对象中的其他东西吗?否则您可以直接将项目传递给函数:

    {multiChoiceArray.map(questionChoice => {
      return (
        <button type="button" key={questionChoice.id} onClick={() => handleClick(questionChoice)}>
          {questionChoice.text}
        </button>
      )
    }
    
    
    // parent file
    testClick = obj => {
       console.log(obj)
    }
    

    【讨论】:

    • 输出是[object Object],有没有办法输出object的props?
    • 哦,好吧,我忘了,你这样传递对象: value={JSON.stringfy(questionChoice)} 然后你可以使用: JSON.parse(event.currentTarget.value)
    • 我收到一个错误:TypeError: JSON.stringfy is not a function
    • 尝试我刚刚更新的第二个选项,我想这是解决这种情况的最佳方法,或者您可以修复 TypeError,我写错了...JSON.stringify(questionChoice)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多