2017-06-22 38 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