JSX使用React,JSX:如何检索输入值,将其作为元素发布,然后清除以重复进行

时间:2018-07-30 16:40:36

标签: javascript reactjs button input jsx

这是学校的作业。它涉及使用React和JSX创建输入字段和提交按钮。单击按钮时,输入值应呈现为主体的元素。我能够在第一次点击时创建它,但不知道如何重复。

如果您看下面的代码,您会看到,当用户键入内容时,handleChange更改输入状态,而单击按钮时,handleClick更改按钮的布尔状态(称为“ post”)。如果post为true,则将输入内容与时间戳一起呈现为标题。

问题在于渲染后,输入未清除。如果用户更改了输入并再次单击按钮,它将使用新的时间戳和新的输入来更新标题,而不添加其他标题。

我尝试过更改输入状态以及在handleClick,handleChange,componentDidMount和componentDidUpdate中发布的状态。但这反复调用setState,我收到一条错误消息“超出最大更新深度”。

因此,我要执行的操作是每次用户单击发布按钮时都发布输入值的新标题。我也希望它清除输入/占位符文本。

import React, { Component } from 'react';
import './App.css';
import Firstposts from './firstposts.jsx';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      input: "",
      post: false
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleChange(event) {
    this.setState({ input: event.target.value });
  }

  handleClick() {
    this.setState({
      post: true
    })
  }

  render() {
    let timestamp = new Date();

    return (
      <div className="container">

        <div className="panel">
          <img height="100 px" src="https://marketing.twitter.com/content/dam/marketing-twitter/brand/logo.png" alt=""></img>
          <h1>Chirper</h1>
        </div>

        <div className="body">
          <input
            placeholder="type your message here"
            onChange={this.handleChange}
          />
          <button
            onClick={this.handleClick}
          >Post</button>
          <h2>Log</h2>
          {<Firstposts />}
          {this.state.post ?
            <div>
              <h3>{timestamp.toString()}</h3>
              <h4>{this.state.input}</h4>
            </div>
            :
            <div />
          }
        </div>

      </div >
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

更新您的handleClick方法以将posts设置为帖子数组,而不是布尔值:

handleClick() {
  this.setState({
    posts: [
      ...this.state.posts,
      this.state.input
    ]
  })
}

这会将this.state.input的值添加到this.state.posts的末尾,并保留所有以前的帖子。

您可以进一步更新它以清除输入字段的值:

handleClick() {
  this.setState({
    posts: [
      ...this.state.posts,
      this.state.input
    ],
    input: '' // add this line to clear your input field when a new post is submitted
  })
}

此外,请确保将<input>中的value设为this.state.input

<input
  value={this.state.input}
  placeholder="type your message here"
  onChange={this.handleChange}
/>

否则,您将无法使用<input>以编程方式更新setState字段的值。您可以在uncontrolled components in React上阅读更多内容。

然后,将您的render方法更新为map上的this.state.posts并呈现每个方法:

{this.state.posts.map(post => (
  <h4>{post}</h4>
))}

您可以在rendering lists in React上阅读更多内容。