简体   繁体   English

如何使用 useRef 为 react class 组件中的组件设置样式?

[英]How to use useRef to style a component in react class component?

I am trying to call an element inside the following component我正在尝试在以下组件中调用一个元素

` `

<ChartRendererCustomised ref={this.componentRef} vizState={DashboardChapterSummaryItemsTop[0].vizState} />

` `

declared the variable as `将变量声明为`

    this.componentRef = React.createRef(null)

` `

and when trying to edit there are some errors such as并且在尝试编辑时出现一些错误,例如这是我实际上要编辑的部分

okay now I changed the method to好的,现在我将方法更改为

  insideTheRef() {
    console.log("button clicked");
    this.componentRef.current.focus()
    console.log("the consoled reref", this.componentRef.current);
  }

here I cannot access componentRef and gets the error "Uncaught TypeError: Cannot read properties of undefined (reading 'componentRef')"在这里我无法访问 componentRef 并收到错误“Uncaught TypeError: Cannot read properties of undefined (reading 'componentRef')”

I tried multiple methods from google but none worked out, I am new to class components and only familiar with functional components我尝试了谷歌的多种方法但没有成功,我是 class 组件的新手,只熟悉功能组件

You cannot use hooks in the class components.您不能在 class 组件中使用挂钩。 The React Hooks are meant to use in functional components. React Hooks 旨在用于功能组件。 There are different life cycles in React Class Components, you can use according to your need. React Class 组件中有不同的生命周期,您可以根据需要使用。 You can directly style element using inline style attribute or external styling using classes.您可以使用内联样式属性或使用类的外部样式直接设置元素样式。

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

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