how to trigger react component from other componen

2019-07-27 02:13发布

问题:

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>