Невозможно получить ввод из текстового поля в React - PullRequest
0 голосов
/ 27 февраля 2020

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

Я даже пытался следовать этому https://reactjs.org/docs/refs-and-the-dom.html, но я не правильно понимаю?

class Activity extends Component {

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

callAPI() {
    fetch("http://localhost:5000/activities", {
        method: 'POST',
        body: JSON.stringify({
            newName: this.newActivity.current,
            oldName: this.state.activity
        }),
    })
        .then(function (response) {
            return response.json()
        });
}



state = {
    activity: this.props.data.name
}
render() {
    return (
        <React.Fragment>
            <Grid justify="center" container spacing={(2, 10)} aligncontent="center">
                <Grid item xs={8} >
                    <Paper>
                        {/*Trying to get the input here so that I can put it into my POST request*/}
                        <TextField inputRef={el => this.newActivity = el} type="activity" id="standard-basic" label="Standard" defaultValue={this.state.activity} />
                    </Paper>
                </Grid>
                <Grid item xs={2}>
                    <Button onClick={this.callAPI} variant="contained" startIcon={<UpdateIcon />} style={buttonStyle} >Uppdatera</Button>
                </Grid>
                <Grid item xs={2}>
                    <Button variant="contained" startIcon={<DeleteIcon />} style={buttonStyle} >Ta Bort</Button>
                </Grid>

            </Grid>
        </React.Fragment>
        );
    }
}

Я получаю ошибку

TypeError: Невозможно прочитать свойство 'newActivity' из неопределенного

Ответы [ 2 ]

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

Вы должны инициировать значения состояния внутри конструктора.

Также измените эту строку как inputRef={this.newActivity} вместо inputRef={(el)=>this.newActivity =el}. Поскольку вы уже создаете ref с помощью createRef, нет необходимости создавать снова.

class Activity extends Component {

constructor(props) {
    super(props);
    this.state = {
        activity: this.props.data.name
    }
    this.callAPI = this.callAPI.bind(this);
    this.newActivity = React.createRef();
}

callAPI() {
    fetch("http://localhost:5000/activities", {
        method: 'POST',
        body: JSON.stringify({
            newName: this.newActivity.current,
            oldName: this.state.activity
        }),
    })
        .then(function (response) {
            return response.json()
        });
}

render() {
    return (
        <React.Fragment>
            <Grid justify="center" container spacing={(2, 10)} aligncontent="center">
                <Grid item xs={8} >
                    <Paper>
                        {/*Trying to get the input here so that I can put it into my POST request*/}
                        <TextField inputRef={this.newActivity} type="activity" id="standard-basic" label="Standard" defaultValue={this.state.activity} />
                    </Paper>
                </Grid>
                <Grid item xs={2}>
                    <Button onClick={this.callAPI} variant="contained" startIcon={<UpdateIcon />} style={buttonStyle} >Uppdatera</Button>
                </Grid>
                <Grid item xs={2}>
                    <Button variant="contained" startIcon={<DeleteIcon />} style={buttonStyle} >Ta Bort</Button>
                </Grid>

            </Grid>
        </React.Fragment>
    );
}
0 голосов
/ 28 февраля 2020

TextField является компонентом-оболочкой.

Вы можете передать ref собственному input следующим образом:

import React, { Component, createRef } from 'react';

import TextField from '@material-ui/core/TextField';

export default class App extends Component {
  ref = createRef();

  render() {
    return (
      <div className="App">
        <TextField inputProps={{ ref: this.ref }} />
      </div>
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...