Реагировать ссылка не определена - PullRequest
0 голосов
/ 19 февраля 2020

, поэтому у меня возникли небольшие проблемы с использованием ссылок с React.

Все, что я пытаюсь сделать, это напечатать текстовое содержимое элемента с помощью ссылок вот так:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}

Тем не менее, это всегда печатает ноль или неопределенный вместо «Привет», что я хочу.

Ответы [ 3 ]

1 голос
/ 19 февраля 2020

Вы входите в консоль в конструкторе до фактического отображения Dom. Вместо этого попробуйте войти в консоль обработчика onClick.

export default class SomeClass extends Component {
 constructor(props) {
  super(props);
  this.intro = React.createRef();
 }
 print = () => {
   console.log(this.intro.textContent);
 }
 render() {
   return (
     <div>
       <div ref={this.intro}>Hi</div>
       <button onClick={this.print}>Print</div>
     </div>
   )
 }

}

1 голос
/ 19 февраля 2020

Вы должны использовать current с ref, например this.ref.current.textContent

Проверьте демонстрацию стекаблиц Здесь

export default class App extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
  }

 componentDidMount(){
      console.log( this.intro.current.textContent);
    }

 render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
1 голос
/ 19 февраля 2020

Это потому, что вы регистрируете его в конструкторе. Запустите код в componentDidMount lifecyle.

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();

  }


componentDidMount(){
      console.log(this.intro.textContent);
    }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
...