LoginSignup
0
2

More than 5 years have passed since last update.

#簡潔 propsの値を自身のイベントで変更させる方法 #忙しい人のためのシリーズ

Last updated at Posted at 2019-02-19

ユースケース

  • ダイアログの開閉
    • ダイアログを 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属性が実行される
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2