2016-09-28 56 views
0

我想從其他組件觸發反應組件。什麼是最好的方式來做到這一點?我不想在像「shouldShowMenu」這樣的redux商店上創建新的標誌。我在思考靜態方法的反應,但我不擅長反應。如何從其他組件觸發反應組件

import Menu from './component/menu' 
const clickfeed =() => {Menu.staticClickEvent()} 
<Provider> 
    <Menu> 
    <Feed onClick={clickfeed}/> 
</Provider> 

我可以使用像這樣的靜態方法,我應該使用靜態方法更改組件狀態。

回答

1

您應該繼續並在您的redux商店中創建shouldShowMenu標誌。一旦你以這種方式進行組件交互,它就是一個應用程序狀態。起初看起來過度,但是一旦你開始擁有一個跨組件共享的價值,這將爲你節省很多麻煩!

+0

呀,謝謝你。我應該以這種方式繼續前進。你知道我們何時應該在反應組件中使用靜態方法嗎? –

0

你不需要redux這個。您可以使用ref來執行此操作。希望能幫助到你!

<script src="https://unpkg.com/[email protected]/browser.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id="container"></div> 
 
<script type="text/babel"> 
 
//component 1 
 
    var Hello = React.createClass({ 
 
    func: function() { 
 
     console.log('I\'m inside Hello component') 
 
    }, 
 
    render: function() { 
 
     return <div > Hello World< /div>; 
 
    } 
 
    }); 
 

 

 
//component 2 
 
    var Hello2 = React.createClass({ 
 
    componentDidMount(){ 
 
    //calling the func() of component 1 from component 2 using ref 
 
    \t this.refs.hello.func() 
 
    }, 
 
    render: function() { 
 
     return <Hello ref="hello"/>; 
 
    } 
 
    }) 
 

 

 
ReactDOM.render(< Hello2/> , 
 
    document.getElementById('container') 
 
); 
 

 
</script>