2016-10-03 129 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} /> 
    ); 
    }, 
}); 
相關問題