如何触发其他组件的反应组件 [英] how to trigger react component from other component

查看:75
本文介绍了如何触发其他组件的反应组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想触发其他组件的react组件。最好的方法是什么?我不想在redux商店(如 shouldShowMenu)上创建新标志。我在反应中考虑静态方法,但我不是反应专家。

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.

推荐答案

您不需要 redux 。您可以使用 ref 来执行此操作。希望对您有所帮助!

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>

这篇关于如何触发其他组件的反应组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆