簡體   English   中英

ref在此reactjs組件中不起作用

[英]ref does not work in this reactjs component

我想在單擊錨點時更改span元素的css類

我將在onclick回調中修改css類

class Button extends Component {
  handleCallback() {
    this.icon.className = this.icon.className + ' wiggle'
  }
  render() {
    return (
      <div>
        <span className='highlight'>{this.props.summary}</span>
        <a  
          className='link'
          onClick={this.handleCallback}
        >   
          <span ref={(c) => this.icon = c} className='icon-up'></span>
        </a>

      </div>
    );  
  }
}

為此,我需要能夠引用該組件。 這就是為什么我在span類中使用ref屬性。

但是,當回調被調用時,出現此錯誤:

Uncaught TypeError: Cannot read property 'icon' of null

為什么ref在這里不起作用?

您在這里缺少一些東西

首先,您正在編寫一個ES6組件類,當將ES6與React一起使用時,React不再具有this功能的自動綁定功能,因此您對handleCallback的調用將引用this ,該結果將為null。

this.handleCallback.bind(this)或使用箭頭函數handleCallback = () => {}聲明回調將解決該問題。

其次,不允許使用試圖設置className的方式,React僅在重新渲染時更新樹(即您看到的內容),而且React永遠不會將您“內聯”的更改刷新回DOM中,因此您必須使用this.setState()this.forceUpdate()才能看到,但是由於更改是內聯的,因此它們將永遠不會在后續渲染中保留。

下面是一個非常詳細的組件,以說明如何執行此操作

class Button extends React.Component {
  constructor() {
    super();
    this.state = {
      shouldWiggle: false
    };
  }
  handleCallback() {
    this.setState({shouldWiggle: !this.state.shouldWiggle});
  }
  render() {
    let cls = this.state.shouldWiggle ? 'icon-up wiggle': 'icon-up';
    return (
      <div>
        <span className='highlight'>{this.props.summary}</span>
        <a  
          className='link'
          onClick={this.handleCallback.bind(this)}
        >   
          <span ref={(c) => this.icon = c} className={cls}>ad</span>
        </a>

      </div>
    );  
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM