我在父组件中有一个按钮组件,需要按钮组件来处理单击按钮元素的按钮样式,而父按钮处理单击Btn 组件
我已经让clickHandler在Btn组件中工作,但不是父组件。最好的方法是什么?
// button component
class BtnFav extends React.Component {
constructor(props) {
super(props);
this.state = {favorited: false};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({favorited: !this.state.favorited});
}
render() {
var btnStyle = this.state.favorited ? 'btn-fav' : 'btn-notfav';
var btnText = this.state.favorited ? 'FAVORITED' : 'NOT FAVORITED';
return (
<button className={btnStyle} onClick={this.handleClick}>{btnText}</button>
);
}
};
// parent
class BtnParent extends React.Component {
constructor(props) {
super(props);
this.alsoDoThis = this.alsoDoThis.bind(this);
}
alsoDoThis() {
alert('Also do this.');
}
render() {
return (
<BtnFav onClick={this.alsoDoThis} />
);
}
};
ReactDOM.render(
<BtnParent />,
document.getElementById('container')
);