【问题标题】:Prevent checkbox and clickable table row conflict防止复选框和可点击表格行冲突
【发布时间】:2017-11-25 15:14:16
【问题描述】:

我在该行中有一个可点击的表格行和复选框。当用户单击该行时,用户将被重定向到其他页面。这是预期的行为。现在的问题是当用户单击复选框时,用户也将被重定向到其他页面。这不是预期的行为。点击复选框不应该触发redirect()方法

  handleChange(e) {
    this.setState({
      checkbox: e.target.checked,
    });
  }

  redirect() {
    Router.push('/registration/register/RegisterEditor', '/verification/e7fe5b68-94e8-435f-8303-5308fd1f7e69');
  }

              <tbody>
                {inventory.list().map((data, index) => (
                  <tr key={'asset'.concat(index)} onClick={() => { this.redirect(); }} tabIndex={index + 1} role="button">
                    <td className="text-center">{index + 1}</td>
                    <td>{data.item}</td>
                    <td width="3%">
                      <Input className="mx-auto" type="checkbox" onChange={this.handleChange} />
                    </td>
                  </tr>
                ))}
              </tbody>

输出:

我该如何解决这个问题?提前致谢。

【问题讨论】:

  • 您是否在复选框点击处理程序中尝试过stopPropagation
  • 是的,我在handleChange() 方法中添加了e.stopPropagation(); 但没有用。

标签: javascript reactjs checkbox


【解决方案1】:

看看这个sn-p:https://codesandbox.io/s/qx6Z1Yrlk

你有两个选择:

在你的重定向函数中添加一个 if 语句,检查点击了什么元素,并且只在它是行时才重定向(确保你传入事件)。

或者,也监听复选框上的单击事件,传入事件,并阻止事件冒泡到行元素。 stopPropagation 在 change 事件侦听器中不起作用,因为 click 事件在 change 事件之前触发。

【讨论】:

  • 感谢您的意见。很有帮助。
  • “stopPropagation 在更改事件侦听器中不起作用,因为在更改事件之前触发了单击事件” - 这就是我所缺少的!谢谢!
【解决方案2】:

您可以在子级的点击处理程序中使用stopPropagation 来停止向父级传播:

const Parent = props => {
  return (
    <div className="parent" onClick={props.onClick}>
      <div>Parent</div>
      {props.children}
    </div>)
}
const Child = props => {return (<div className="child" onClick={props.onClick} >child</div>) }

class Wrapper extends React.Component{
  constructor(props){
    super(props);
    
    this.onParentClick = this.onParentClick.bind(this);
    this.onChildClick = this.onChildClick.bind(this);
  }
  
  onParentClick(e){
    console.log('parent clicked');
  }
  
  onChildClick(e){
    e.stopPropagation();
    console.log('child clicked');
  }
  
  render(){
    return(
      <Parent onClick={this.onParentClick}>
        <Child onClick={this.onChildClick} />
      </Parent>
    );
  }
}

ReactDOM.render(<Wrapper/>,document.getElementById('app'))
.parent{
  box-shadow: 0 0 2px 1px #000;
  min-height: 60px;
  padding: 10px;
  cursor: pointer;
}

.child{
  box-shadow: 0 0 1px 1px red;
  min-height: 10px;
  max-width: 40px;
  padding: 1px;
  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>

【讨论】:

  • 感谢您的意见。很有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多