Реакция привязки ref приводит к: TypeError: Невозможно прочитать свойство 'focus' из null - PullRequest
0 голосов
/ 22 ноября 2018

Я могу скопировать пример в документации React, чтобы создать ссылку, а затем настроить ее на изолированную программную среду кода, но по какой-то причине я не могу воспроизвести ее в локальном проекте.Я использую реагировать 16.6.3, которая является последней версией.

TypeError: Cannot read property 'focus' of null
SelectDonation.save_donation_amount
src/components/SelectDonation.js:19
  16 | save_donation_amount () {
  17 |   
  18 |   // testing refs
> 19 |   this.customDonationInput.current.focus();
     | ^  20 |   
  21 |   // prevent pageload
  22 |   // grab the custom amount

Вот мой компонент:

import React from "react";
import {Button, Modal, Form, Input, Radio} from 'semantic-ui-react';
import store from "../reducer";

export default class SelectDonation extends React.Component {
  constructor(props) {
    super(props);
    this.customDonationInput = React.createRef();
    this.save_donation_amount = this.save_donation_amount.bind(this);
  }

  save_donation_amount () {
    this.customDonationInput.current.focus();
  };

  render() {
    return (
        <Form>
            <Form.Input
              type='number'
              placeholder='Custom Amount'
              name='donation_amount'
              id='custom_amount'
              ref={this.customDonationInput}
              // value={store.donation_amount}
              defaultValue={store.donation_amount}
            />

            <Button
              primary
              onClick={
                this.save_donation_amount
              }>Next Step
            </Button>
        </Form>
    )
  }
}

Из ошибки кажется, что свойство .current отсутствует,Что может быть причиной этого?

1 Ответ

0 голосов
/ 23 ноября 2018

Ошибка вызвана тем, что <Form.Input> в Semantic UI React является функциональным компонентом и поэтому не может получать ссылки.Изменение элемента на обычный <input> исправило проблему

...