2016-07-18 25 views
0

我有一個樣式的Btn組件在該組件內的onClick中切換。在Btn組件和父母的反應 - onClick處理程序

我想添加一個onClick到父按鈕被點擊時執行一個函數。 btn組件將被重用,所以父組件中的onClick將會改變,而Btn組件中的onClick將總是隻能切換btn樣式。

FIDDLE

class BtnParent extends React.Component { 
constructor(props) { 
    super(props); 
    this.alsoDoThis = this.alsoDoThis.bind(this); 
    } 
    alsoDoThis() { 
    alert('clicked'); 
    } 
    render() { 
    return (
     <BtnFav onClick={this.alsoDoThis} /> 
    ); 
    } 
}; 
+0

''? –

回答

0

您傳遞onClick道具的孩子,但你永遠不使用後援功能需要被顯式調用:

handleClick() { 
    this.props.onClick(); // invoke it anywhere in the child 
    this.setState({favorited: !this.state.favorited}); 
} 
0

btnParent.jsx如下:

class BtnParent extends React.Component { 
constructor(props) { 
    super(props); 
    this.alsoDoThis = this.alsoDoThis.bind(this); 
    } 
    alsoDoThis() { 
    alert('clicked'); 
    } 
    render() { 
    return (
     <BtnFav alsoDoThis={this.alsoDoThis} /> 
    ); 
    } 
}; 

btnFav.jsx如下:

class BtnFav extends React.Component { 
    render() { 
    return (
     <button onClick={this.props.alsoDoThis} /> 
    ); 
    } 
}; 

可以解決它!父母和孩子之間


組件通信,可以使用道具反應傳遞function,但是當兩個組件都沒有父/子,你可以使用一些事件發佈/訂閱庫。如https://github.com/hustcc/onfire.js

+0

這使得alert('clicked')工作,但它打破了按鈕組件內處理的樣式更改。這裏是你的代碼更新小提琴:https://jsfiddle.net/69z2wepo/49594/ –

+0

不錯,它可以工作~~ – atool

0

嘗試了這一點,

class BtnFav extends React.Component { 
     render() { 
     return (
      <button onClick={()=>this.props.alsoDoThis()} /> 
     ); 
     } 
    };