【问题标题】:React onClick not propagating event反应 onClick 不传播事件
【发布时间】:2021-01-12 20:36:18
【问题描述】:

我创建了一个新的 reactjs 项目,不知何故 onClick={() => console.log('clicked...')} 不会传播事件,即使该组件是在 DOM 上呈现的。

但是,当我在 JSFiddle 上尝试时,相同的代码会传播一个事件。

请帮忙。

编辑

import React from 'react'


const Key = props => {
    return (<button
     style={style} 
     className={'calc-key ' + props.element.name} 
    //  onClick={props.handleButtonClick}
     onClick={() => console.log('Clicked...')}
     >
        {props.element.value}
    </button>)
}

const style = {
    width: '33%',
    textAlign: 'center',
    padding: '1em',
    fontWeight: '800',
    cursor: 'pointer',
    zIndex: '100'
    
}

export default Key;

【问题讨论】:

  • 你能给我们看一个运行代码吗?我们不能用这一行做任何事情

标签: javascript reactjs dom-events


【解决方案1】:
import React from 'react'

const Key = props => {
  return (<button
    style={style}
    className={'calc-key ' + props?.element?.name}
    onClick={() => console.log('Clicked...')}
  >
    {props?.element?.value}
  </button>)
}

const style = {
  width: '33%',
  textAlign: 'center',
  padding: '1em',
  fontWeight: '800',
  cursor: 'pointer',
  zIndex: '100'

}

export default Key;

我试过你的代码,它很有用。

【讨论】:

  • 可悲的是,没有运气酋长。
  • 感谢您的回复。我认为这与我的设置有关。我最初使用 NPM 设置了 react 应用程序。现在我使用 create-react-app 创建了一个新项目,在那里复制了组件,一切正常。非常感谢。
猜你喜欢
  • 2015-12-05
  • 1970-01-01
  • 2017-07-24
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2014-05-06
相关资源
最近更新 更多