Реакция ссылки на доступ к измерению узла имеет текущий как ноль - PullRequest
0 голосов
/ 05 февраля 2019

Я пытаюсь использовать React.createRef() для доступа к измерениям элемента DOM в React.

Я создаю в конструкторе как

constructor(props) {
super(props);
this.container = React.createRef()
}

И назначаю его как

  <div id="container"
  ref={this.container}
  >...children</div>

Однако, когда я выхожу изнутри componentDidMount()

componentDidMount(){
console.log(this.container);
}

, я вижу {current: null} в консоли.Но если я разверну этот объект, я увижу все, к чему я хочу получить доступ, например clientHeight со значением.

enter image description here

Как получить доступ к этим атрибутам?В настоящий момент this.container.current.clientHeight возвращает ноль.

Спасибо

1 Ответ

0 голосов
/ 05 февраля 2019

вот мой пример кода:

class Badge extends React.Component {
constructor(props) {
super(props);

this.textWidth = React.createRef();
this.state = {
  width: ""
};
}

 componentDidMount() {
this.textWidth.current.addEventListener("load", this.getWidth());
}

 getWidth = () => {
this.setState({
  width: this.textWidth.current.clientWidth + 30
 });
};

render() {
  return (
  <div
    style={{
      width: this.state.width
     }}
     className="badge"
   >
     <p ref={this.textWidth}>{this.props.children}</p>
   </div>
  );
  }
 }
...