简体   繁体   English

span不会触发OnClick内部列表反应子组件

[英]span does not firing OnClick inside list react child component

I have 2 components when the parent trigger by OnClick the child which has span element doesn't fire OnClick at all. 当我通过OnClick触发父级时,我有两个组件,具有span元素的子组件根本不会触发OnClick。 I try it when the parent is button and it works perfectly but when the parent is list it doesn't trigger the child. 我在父母是按钮时尝试它并且它完美地工作但是当父亲是列表时它不会触发孩子。

class Menu extends Component {
 handleItemClick=(e)=>{
     // whatever ..
 }
 render(){
  return(
   <ul>
     {
       items.map((item, i)=>(
            <li key={i}
                id={i}
                onClick={this.handleItemClick}>
                <Child />
                {item}
            </li>
        ))
     }
   </ul>
  )
}

class Child extends Component {
 handleSpanClick=(e)=>{
     console.log("It works!")
 }
 render(){
  return(
   <span onClick={this.handleSpanClick}></span>
  )
}

This looks like its probably because the span defaults to an inline element and if you haven't styled it will have 0 width so it wont have a clickable area. 这可能是因为它可能是因为span默认为内联元素,如果你没有样式,它将具有0宽度,因此它没有可点击区域。 Try putting some text in so it actually has a clickable area to test. 尝试放入一些文本,以便它实际上有一个可点击的区域来测试。 If this works style it with CSS (display: block, width, height etc). 如果这适用于CSS(显示:块,宽度,高度等)的样式。

@bunion's answer is correct! @ bunion的答案是对的!

It doesn't trigger your handleSpanClick() handler, because the <span></span> you are rendering is empty. 它不会触发handleSpanClick()处理程序,因为您渲染的<span></span>为空。

Either place some content in it, or either tweak the CSS display property - change it to block or inline-block and add some height and width . 要么在其中放置一些内容,要么调整CSS显示属性 - 将其更改为blockinline-block并添加一些heightwidth While developing, you can also set a background color, so you actually see where your <span></span> is. 在开发过程中,您还可以设置背景颜色,以便实际看到<span></span>位置。

You're code is just fine. 你的代码很好。 Here's a prove, run this snippet: 这是一个证明,运行此片段:

 class Menu extends React.Component { handleItemClick=(e)=>{ /* whatever .. */ } render() { return( <ul> { this.props.items.map((item, i) => ( <li key={i} id={i} onClick={this.handleItemClick}> <Child /> {item} </li> ))} </ul> ) } } class Child extends React.Component { handleSpanClick=(e)=>{ console.log("It works!"); } render(){ return ( <span onClick={this.handleSpanClick}> CLICK ME (I am span) </span> ); } } ReactDOM.render(<Menu items={[ '-- I am list item, 1', '-- I am list item, 2', '-- I am list item, 3' ]} />, document.getElementById('app') ); 
 /* So we could see better where it is */ span { background-color: lightgreen; cursor: pointer; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM