@testtoster

Как вывести state по нажатию на кнопку?

Есть state. Скажите, как мне вывести count 0 в новый абзац на странице при нажатии на кнопку Count?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      count: 0,
    }
  }

  showText = () => {
    console.log('button work');
    this.setState({ text: 'button work' });
  }

  showCount = () => {
    this.setState({ text: '0' });
  }

  render() {
    return (
      <div>
        <button onClick={this.showText}>Push1</button>
        <p>{this.state.text}</p>
        <button onClick={this.showCount}>Count</button>
        <p>{this.state.count}</p>
      </div>
    )
  }
}
  • Вопрос задан
  • 186 просмотров
Решения вопроса 1
GreyCrew
@GreyCrew
Full-stack developer
Тогда я думаю в методе showCount стоит менять count, а не text
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      count: 0,
    }
  }

  showText = () => {
    console.log('button work');
    this.setState({ text: 'button work' });
  }

  showCount = () => {
    this.setState({ count: '0' });
  }

  render() {
    return (
      <div>
        <button onClick={this.showText}>Push1</button>
        <p>{this.state.text}</p>
        <button onClick={this.showCount}>Count</button>
        <p>{this.state.count}</p>
      </div>
    )
  }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы