简体   繁体   English

如何从自定义挂钩访问 React 中的 DOM 元素?

[英]How to access a DOM element in React from a custom hook?

I have a function responsable for setting a height dynamically to an element, this function is being triggered from multiple components, some of them are children of the component which has the function and other aren't.我有一个 function 负责动态设置元素的高度,这个 function 是由多个组件触发的,其中一些是具有 function 的组件的子级,而其他则不是。

This implies two problemas, concerning the children components I have to pass the function down the tree for multiple levels as a callback, and about those that are not children I have to use document.getElementById to access the element, what is not ideal when it comes to react, besides that I have to build the same function for every non-chldren component.这意味着两个问题,关于子组件,我必须将 function 作为回调向下传递到树的多个级别,关于那些不是子组件的组件,我必须使用document.getElementById来访问元素,当它不理想时开始做出反应,除此之外,我必须为每个非儿童组件构建相同的 function。

In order to make things more clean and maintainable I converted the funtion to a hook that makes this DOM manipulation (this is a hook and not a common function, because I need to call another hook from it), but I still have to use document.getElementById to access the target element.为了使事情更干净和易于维护,我将函数转换为一个钩子来进行 DOM 操作(这是一个钩子而不是常见的 function,因为我需要从中调用另一个钩子),但我仍然必须使用document.getElementById访问目标元素。

What I want to do is if is there a more react way for accessing the element?我想做的是是否有更反应的方式来访问元素? Like accessing a ref from a component outside the tree for instance?例如,就像从树外部的组件访问ref一样?

在此处输入图像描述

Create a context:创建上下文:

height-context.jsx

const HeightContext = createContext();

export const HeightContextProvider = ({ children }) => {
  const [height, setHeight] = useState();

  return (
    <HeightContext.Provider value={{ height, setHeight }}>{children}</HeightContext.Provider>
  )
}

const useHeightContext = () => {
  const context = useContext(HeightContext);

  if (!context) throw Error('HeightContext must be used within HeightContextProvider ');

  return context;
}

app.jsx (or any other component that is a common ancestor of component P and O) app.jsx (或作为组件 P 和 O 的共同祖先的任何其他组件)

const App = () => {
  return (
    <HeightContextProvider>
      // other components
    </HeightContextProvider>
  )
}

child.jsx (or any component where you will change height) child.jsx (或您将更改高度的任何组件)

const Child = () => {
  const { setHeight } = useHeightContext();

  return (
    <button onClick={() => setHeight(100)}>change height</button>
  )
}

manipulated-component.jsx

const ManipulatedComponent = () => {
  const { height } = useHeightContext();

  return (
    <div style={{ height }}>
      //other components
    </div>
  )
}

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

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