ユースケース
- ダイアログの開閉
- ダイアログを open={true} で開いたが、ダイアログ自身が持つ×ボタンを押したら open: false にしたい
以下で実現
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
open: this.props.open
};
}
componentWillReceiveProps(nextProps) {
this.setState({ open: nextProps.open });
}
render() {
return (
<Dialog
open={this.state.open}
onClose={this.props.onClose}
>
{this.props.children}
<div className="close" onClick={()=> {
this.setState({ open: false });
this.props.onClose();
}}>×</div>
</Dialog>
);
}
}
ポイント
-
componentWillReceiveProps
でMount後のpropsの変化にも対応- これで "一度しか開かない" なんてことが起こらない
-
this.props.onClose();
を呼ぶ- これでこのコンポーネントのonClose属性が実行される