2017-06-22 41 views
1

我有一个可点击的表格行和该行中的复选框。当用户点击该行时,用户将被重定向到其他页面。这是预期的行为。现在问题出在用户点击复选框时,用户也会被重定向到其他页面。这不是预期的行为。点击复选框不应触发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> 

输出:

enter image description here

我怎样才能解决这个问题?提前致谢。

+1

你试过'stopPropagation'中的复选框单击处理程序? –

+0

是的,我在'handleChange()'方法中添加'e.stopPropagation();'但没有工作。 – sg552

回答

2

看一看这个片段:https://codesandbox.io/s/qx6Z1Yrlk

你有两个选择:

添加if语句在您的重定向功能检查已经被点击了哪些元素,只有当它的行重定向(使确定你通过事件)。

或者,还可以在复选框上侦听单击事件,传递事件并停止事件冒泡到行元素。 stopPropagation将无法在更改事件侦听器中工作,因为click事件在更改事件之前触发。

+0

感谢您的意见。这很有帮助。 – sg552

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>

+0

感谢您的意见。这很有帮助。 – sg552