A
A
Alexey Milyutin2019-05-05 18:49:59
JavaScript
Alexey Milyutin, 2019-05-05 18:49:59

What am I doing wrong when overwriting state?

Hello, why is the state not overwritten with a new one and what errors and bad practices do you see in my code?

class Li extends React.Component {
  render() {
    return (
      <li>{this.props.text}</li>
    )
  }
}

class Elem extends React.Component {
  render() {
    return (<div className="element">
      <ul>
        <Li text={this.props.text}/>
      </ul>
    </div>)
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {text: 'hello world'};
  }
  render() {
    return (
      <div className="pageWrapper">
        <h1>To Do List</h1>
        <input placeholder="Введите текст" onChange={this.submitText} type="text" className="inp"/>
        <Elem text={this.state.text}/>
      </div>
    )
  }
  submitText() {
    let inpValue = document.querySelector(".inp").value;
    this.setState({
      text: inpValue
    });
  }
}

ReactDOM.render(<App />, document.querySelector("#app"));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-05
@doppelgangerz

The context is lost. Well, you don't have to try to reach the element through the querySelector - it is available as the target property of the event object.

submitText = (e) => {
  this.setState({
    text: e.target.value,
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question