简体   繁体   English

react.js使DOM元素可用于顶级父主组件

[英]react.js make DOM element available to top parent main component

I need to execute click events (probably using EventTarget.dispatchEvent()) on certain DOM elements that are nested quite deeply in my component hierarchy. 我需要对嵌套在组件层次结构中的某些DOM元素执行单击事件(可能使用EventTarget.dispatchEvent())。 I need to trigger those click events from the top parent App component. 我需要从顶级父应用程序组件触发那些点击事件。

How would you approach this? 您将如何处理? I don't want to pass down a callback function to each of those components as they are nested so deeply. 我不想将回调函数传递给这些组件中的每个组件,因为它们嵌套得非常深。 Is there away of making their DOM elements available globally / to the parent App component? 是否可以将其DOM元素全局提供给父App组件?

Three options: 三种选择:

  1. Pass the function down with React's context. 通过React的上下文传递函数。
  2. Move the child up to be in the App components render and then use this.props.children to render it in one of the App's nested children. 将子级向上移动到App组件渲染中,然后使用this.props.children在应用程序的嵌套子级之一中渲染它。
  3. Move the click event logic closer to the child component and use Redux/Flux to update the global state which the App can then access (for redux you could pass the function into the global state but this is not recommended as it's not serializable). 将点击事件逻辑移到更靠近子组件的位置,然后使用Redux / Flux更新应用可以访问的全局状态(对于Redux,您可以将函数传递到全局状态,但不建议这样做,因为它不可序列化)。

Option 1 is the easiest but not recommended to use context if you can help it. 选项1是最简单的方法,但如果可以帮助,则不建议使用上下文。 Option 2 may not be possible. 选项2可能是不可能的。 You probably want option 3. 您可能需要选项3。

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

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