これらのログインモーダルのそれぞれをレンダリングするコンポーネントでは、各コンポーネントの小道具を通じて値を渡すことをお勧めします。モーダルコンポーネントでは、渡されたプロパティの値を使用して、モーダルを表示するかどうかを決定します。
ここでは、仕事ができる方法の簡単な例です(理論的には - テストしていません):
ログイン/新規登録モーダル
import React from 'react';
const LoginModal = React.createClass({
propTypes: {
isVisible: React.PropTypes.boolean.isRequired,
onLogin: React.PropTypes.function,
},
componentWillReceiveProps(nextProps) {
// Will allow parent components to pass in a boolean
// telling this component when to render
this.setState({
showModal: nextProps.isVisible,
});
},
onSubmit() {
// TODO: Handle login
// If we let the parent handle the visibility, we just call
// the onLogin callback passed in and don't set this.state.showModal
this.props.onLogin();
},
render() {
return (
// Use this.state.showModal boolean to show/hide
// your login modal
);
},
});
export default LoginModal;
親コンポーネント
import React from 'react';
import LoginModal from './LoginModal';
const ParentComponent = React.createClass({
showLoginModal() {
this.setState({
showLogin: true,
});
},
hideLoginModal() {
this.setState({
showLogin: false,
});
// TODO: Likely change the route or do something else here...
},
render() {
return (
<button onClick={this.showLoginModal}>Login</button>
<LoginModal isVisible={this.state.showLogin} onLogin={this.hideLoginModal} />
);
},
});
コンポーネントツリーの上位のコンポーネントの状態を変更したい場合は、コールバックメソッドをprops tとして渡す必要がありますo基本コンポーネント。 – Alexander