javascript 如何使用 classList 获取 React Component 引用以更改其类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33585491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:39:25  来源:igfitidea点击:

How to get a React Component reference to change its class using classList?

javascriptfacebookreactjs

提问by Muhammad Asif Javed

I have create a React Componentusing the following code. In this i am creating tab and added the class and storing its reference to in a global namespace Interface for further processing.

我使用以下代码创建了一个React 组件。在此我创建选项卡并添加类并将其引用存储在全局命名空间接口中以供进一步处理。

var TabBody = React.createClass({
  getInitialState: function() {
    return {
      class: 'tabBody tab activeTab'
    }
  },
  render: function() {
    Interfaces.tabBody = this;
    tabSelectionInfo.tabBody = this;
    return (
      React.createElement('div', {
          className: this.state.class,
          onClick: handleTabClick
        },
        React.createElement('span', {}, "Body"))
    );
  }
});

now using the following function, To add a class to the above component and console is showing an error undefined. how i store the refrance of this component in order to change its class later.

现在使用以下函数,向上述组件添加一个类,控制台显示未定义的错误。我如何存储这个组件的 refrance 以便以后更改它的类。

handleTabClick = function() {
  Interfaces.tabBody.classList.add('tabPreviewComplete');
}

采纳答案by Awais

As you have specified in your code that your class name is used using a state variable named 'class' containing the value 'tabBody tab activeTab'

正如您在代码中指定的,您的类名使用名为“class”的状态变量使用,该变量包含值“tabBody tab activeTab”

className: this.state.class,

Thats why you must have to use setState() method to change your className. As you have the reference to your class instance in global namespace named 'Interface.tabBody' which can be used to set your className by calling setState() e.g

这就是为什么您必须使用 setState() 方法来更改您的 className。由于您在名为“Interface.tabBody”的全局命名空间中引用了您的类实例,它可用于通过调用 setState() 来设置您的 className,例如

Interface.tabBody.setState({class: 'tabBody tab activeTab disabled'});

This method is used when you want to access class instance outside of the React.

当您想在 React 之外访问类实例时使用此方法。

if you are using handleclick() in your react then you can use the following code

如果您在反应中使用 handleclick() 那么您可以使用以下代码

handleTabClick = function() {
  this.setState({class: 'tabBody tab activeTab disabled'});
}

By calling setState() the React will detect changes and re-renders component.

通过调用 setState(),React 将检测更改并重新渲染组件。

回答by Dominic

That's because thisis the reference to your class instance, not a DOM element. To access DOM elements (since React uses a virtual DOM) you need to create a reference, i.e:

那是因为this是对您的类实例的引用,而不是 DOM 元素。要访问 DOM 元素(因为 React 使用虚拟 DOM),您需要创建一个引用,即:

React.createElement('div', {
  ref: 'tabBody'

You can then access it via this.refs.tabBody

然后您可以通过访问它 this.refs.tabBody

You shouldn't pass this reference outside of the class however. Instead you can pass the reference to handleTabClickwhen the event happens:

但是,您不应该在类之外传递此引用。相反,您可以将引用传递到handleTabClick事件发生时:

React.createElement('div', {
  ref: 'tabBody'
  onClick: e => this.props.handleTabClick(e, this.refs.tabBody)

Then you can do:

然后你可以这样做:

handleTabClick = function(e, tabBody) {
    tabBody.classList.add('tabPreviewComplete');
}

Personally I would change the state though, so that if the component re-renders it has the correct class.

就我个人而言,我会更改状态,以便如果组件重新渲染它具有正确的类。

Fiddle: http://jsfiddle.net/ferahl/dpvb1h3y/

小提琴:http: //jsfiddle.net/ferahl/dpvb1h3y/

回答by YòG?

Above 16.8, using useRefhooks for functional components,

16.8以上,对功能组件使用useRef钩子,

// useRef takes initialValue as param
const fooBarRef = useRef(null);

//DOM Usage
<div className="foo" ref={fooBarRef}>Hello</div>

Above 16.3, using createReffor class components,

16.3以上,对类组件使用createRef

// Creating ref in a constructor
this.fooBarRef = React.createRef();

// DOM usage
<div className="foo" ref={this.fooBarRef}>Hello</div>

Usage of reference for both useRef && createRefafter mounting node element,

安装节点元素后使用useRef && createRef的引用,

//Getting node element
const fooBarNode = this.fooBarRef.current

//Adding class to node element
fooBarNode.classList.add('bar');

Below 16.3, using callBackRef,

在 16.3 以下,使用callBackRef

// Creating ref in a constructor
this.fooBarRef = null;
this.setFooBarRef = (ref) => {
  this.fooBarRef = ref;
}

// DOM usage
<div className="foo" ref={this.setFooBarRef}>Hello</div>

Usage of reference after mounting node element,

安装节点元素后引用的使用,

//Adding class name
this.fooBarRef.classList.add('bar');