简体   繁体   English

在 React 的另一个组件中单击按钮的事件侦听器

[英]Event Listener for button click in another component in React

I am using MapBox in React, where it has a navbar parent.我在 React 中使用 MapBox,它有一个导航栏父项。 I have a button in the navbar component that collapses the navbar by changing it's class, where I also want to execute the code below in the map component when this button is pressed.我在导航栏组件中有一个按钮,通过更改它的 class 折叠导航栏,我还想在按下此按钮时在 map 组件中执行下面的代码。

map.easeTo({
padding: {left:300},
duration: 1000
});

I feel like the function addEventListener() can acomplish this, however the navbar and the map are separate components in two different js files.我觉得 function addEventListener() 可以完成这个,但是导航栏和 map 是两个不同 js 文件中的独立组件。

Thanks for your help.谢谢你的帮助。

Wrap them both in a parent component that keeps the navbar state, then pass the state and the state setter to both children.将它们都包装在保留导航栏 state 的父组件中,然后将 state 和 state setter 传递给两个子组件。 You can also use context, but on that level of nesting it is kind of an overkill您也可以使用上下文,但在嵌套级别上它有点矫枉过正

Example:例子:

const Layout = () => {
  const [isExpanded, setIsExpanded] = useState(false);

  return {
    <>
      <Navbar isExpanded={isExpanded} setIsExpanded={setIsExpanded} />
      <Map isExpanded={isExpanded} setIsExpanded={setIsExpanded} />
    </>
  }
}

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

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