how to trigger react component from other component

早过忘川 提交于 2019-12-11 05:28:42

问题


I want to trigger react component from other component. What is the best way to do it? I don't want to create new flag on redux store like "shouldShowMenu". I thinking about static method in react but i not expert in react.

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

can i use static method like this and should i use static method change the component state.


回答1:


You should go ahead and create that shouldShowMenu flag in your redux store. Once you have components interacting that way, it's an application state. It seems excessive at first but once you start having a value that is shared across components, this will save you a lot of headaches!




回答2:


You don't need redux for this. You can use ref to do this. Hope it helps!

<script src="https://unpkg.com/babel-core@5.8.38/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
  	  this.refs.hello.func()
    },
    render: function() {
      return <Hello ref="hello"/>;
   }
  })


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

</script>


来源:https://stackoverflow.com/questions/39739054/how-to-trigger-react-component-from-other-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!