2016-10-03 59 views
0

我正在使用react进行项目工作,我有一个注册模式和一个登录模式,它们都是独立的组件,我希望有两个链接吃了每个模式的顶部,以便能够从注册模型到登录模式。每个组件模型具有功能开放,看起来像这样:反应:如何从另一个组件访问组件?

open() { 
    this.setState({ showModal: true }); 
    } 

是否有一个组件的方式来调用函数,并从另一个组件组国家或做我需要做两个模型一个组件不知何故?

+0

如果你想改变组件树中更高级的组件的状态,你应该将回调方法作为道具传递o您的基础组件。 – Alexander

回答

4

处理组件之间通信的最佳方法是通过一个应用程序的状态容器,所有组件都“挂钩”。

这里的一个非常简单说明:

// this state is defined somewhere in your application 
// all of your components "hook in to" this state by including 
// the values you want as props. For example, 
//  <MyFancyComponent value={state.value1} /> 
// and now MyFancyComponent has access to value1 
state = { 
    value1: 42, 
    showModal1: false, 
    showModal2: false, 
}; 


// somewhere in your application, there's a render method 
// that looks like this 
render() { 
    return (
     <div> 

      {this.props.showModal1 ? <Modal1 /> : null} 
      {this.props.showModal2 ? <Modal2 /> : null} 

      {/* now render the rest of your component */} 

     </div> 
    ); 
} 

的基本思想是,当这个分量(一个与上面的render方法)需要显示Modal1Modal2,它改变了相应的标志在状态,它们映射到组件上的showModal*道具。然后该组件重新渲染并包含适当的模态。如果你想从另一个组件触发一个模式,你可以在你的应用程序状态中更改相应的标志& React将开始工作,重新渲染并显示模态。

上面的例子是荒谬的不完整 - 它只是为了说明基本思想。为了使这个工作,你需要为你的应用程序实现一个状态容器。为此,我建议使用flux patternredux。现在

,你可以实现此为一组回调&属性所特有的您正在使用的组件,但我建议反对 - 它变得非常难以管理,非常快。此外,它不会扩展 - 要添加组件,您必须手动将其“连线”到所有其他组件。

2

在您渲染每个登录模式的组件中,您希望通过每个组件的道具传递值。在模态组件中,您将使用传入的属性的值来确定是否应显示模态。

下面是它如何可以工作一个简单的例子(理论上 - 没有测试):

登录/注册莫代尔

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} /> 
    ); 
    }, 
}); 
相关问题