简体   繁体   English

调度和侦听不同组件中的事件 - reactjs

[英]Dispatching and listeing for events in different components - reactjs

I am trying to create a custom event in one component and add an event listener in another component. 我试图在一个组件中创建一个自定义事件,并在另一个组件中添加一个事件监听器。 The component that is listening for the event contains a function that I want to execute on the event. 正在侦听事件的组件包含我要在事件上执行的函数。 Below are what I have in the two components, I just feel like I'm going about this in the wrong way... 以下是我在这两个组件中所拥有的内容,我只是觉得我以错误的方式解决这个问题...

Component #1 组件#1

toggleWidget() {
   const event = new CustomEvent('sliderClicked', {
     bubbles: true,
   });
   const sliderToggle = document.getElementById('input');
   sliderToggle.dispatchEvent(event);

   this.setState({
     checked: !this.state.checked,
   });
}
  /* and then in my render... */

 render() {
   const displaySlider = this.state.isSliderDisplayed ? (
     <div className="slider-container" >
    <label className="switch" htmlFor="input">
      <input type="checkbox" checked={this.state.checked} onChange={this.toggleWidget} id="input" />
      <span className="slider round" />
    </label>
    <p className="batch-slider-title"> Batch Widget </p>
  </div>) : null;`

Component Two 第二部分

window.addEventListener('sliderClicked', this.refreshLayout);`

Any ideas as to what I may be doing wrong? 关于我可能做错什么的任何想法?

Basically it should work, but in react - if you rendered an element in a component you can use the ref to access it: 基本上它应该工作,但在react - 如果你在组件中渲染元素,你可以使用ref来访问它:

<input
    type="checkbox"
    checked={this.state.checked}
    onChange={this.toggleWidget}
    id="input"
    ref={(c) => this.input = c}
/>

And your toggleWidget function should be something like this: 你的toggleWidget函数应该是这样的:

toggleWidget() {
    ...
    this.input.dispatchEvent(event);
    ...
}

In React it's pretty common to pass down callbacks from parent to child. 在React中,将回调从父级传递给子级是很常见的。

const Child = ({handleClick}) => (
  <div onClick={ handleClick } >Click me!</div>
);

const Parent = () => {
  const childClickHandler = event => {
    // do stuff
    alert('My child is calling?');
  }

  return (
    <Child handleClick={ childClickHandler }/>
  );
};

Maybe that could work for you? 也许这对你有用吗? You can try the code here. 你可以在这里试试代码。 (JSFiddle) (的jsfiddle)

Refs are generally considered something to avoid in React as they couple components together. Refact通常被认为是React中要避免的,因为它们将组件耦合在一起。 see the documentation here: https://facebook.github.io/react/docs/refs-and-the-dom.html 请参阅此处的文档: https//facebook.github.io/react/docs/refs-and-the-dom.html

Your first inclination may be to use refs to "make things happen" in your app. 你的第一个倾向可能是使用refs在你的应用程序中“让事情发生”。 If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. 如果是这种情况,请花一点时间,更关键地考虑组件层次结构中应该拥有状态的位置。 Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. 通常,很明显,“拥有”该状态的适当位置在层次结构中处于更高级别。 See the Lifting State Up guide for examples of this. 有关此示例,请参阅“提升状态向上”指南。

Try using a global state container like redux and when you "toggleWidget" in one component, set a property in your redux store. 尝试使用像redux这样的全局状态容器,当你在一个组件中“toggleWidget”时,在redux商店中设置一个属性。 Listen to that property by setting it as a prop in your second component(the one that you want to respond to a change/toggle). 通过在第二个组件(要响应更改/切换的组件)中将其设置为道具来收听该属性。 On change of that property your component will have the "componentWillReceiveProps" lifecycle method called and you can then have your "responding" component take whatever action you like. 在更改该属性时,您的组件将调用“componentWillReceiveProps”生命周期方法,然后您可以让“响应”组件采取您喜欢的任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM