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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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"))
    );
  }
});

现在使用以下功能,要向上述组件和控制台中添加类,控制台将显示未定义的错误。我如何存储此组件的refrance以便以后更改其类。

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

在16.8之上,对功能组件使用useRef挂钩,

1
2
3
4
5
// useRef takes initialValue as param
const fooBarRef = useRef(null);

//DOM Usage
Hello

使用参考的用法在安装节点元素后,

1
2
3
4
5
//Getting node element
const fooBarNode = fooBarRef.current

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

在16.3以上版本中,使用createRef作为类组件,

1
2
3
4
5
// Creating ref in a constructor
this.fooBarRef = React.createRef();

// DOM usage
Hello

在安装节点元素

之后,对createRef的引用用法

1
2
3
4
5
//Getting node element
const fooBarNode = this.fooBarRef.current

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

16.3以下,使用callBackRef,

1
2
3
4
5
6
7
8
// Creating ref in a constructor
this.fooBarRef = null;
this.setFooBarRef = (ref) => {
  this.fooBarRef = ref;
}

// DOM usage
Hello

安装节点元素后的参考用途,

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

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

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

然后可以通过this.refs.tabBody

访问它

但是,您不应将此引用传递给全班同学。相反,可以在事件发生时将引用传递给handleTabClick

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

然后您可以做:

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

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

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


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

1
className: this.state.class,

这就是为什么必须必须使用setState()方法更改className的原因。当您在名为'Interface.tabBody'的全局命名空间中引用了您的类实例时,可以通过调用setState()e.g

来设置您的className

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

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

如果您在react中使用handleclick(),则可以使用以下代码

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

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