onSubmit 处理程序在 jsfiddle 中执行,但不在我的开发环境中

onSubmit handler executes in jsfiddle, but not in my development environment

我使用此代码的最终目标是我希望在按下按钮时将输入到文本字段中的数据记录到控制台,但在我的开发环境中不执行 onSubmit 处理程序(顺便说一下,我的环境包括一个使用 create-react-app 设置的开发服务器)。

import React, { Component } from 'react'
import './App.css'

class App extends Component {
  constructor() {
      super()
      this.state = {input: undefined}
  }

  render() {
    return (
      <div className="App" marginTop="200px">
        <div className="App-header">
          <h2>Timestamp Microservice</h2>
        </div>
        <p className="App-intro">
          Converts a Unix timestamp (2365145258) to a natural language date (December 16, 2016) and vice versa.
        </p>
        <form>    
          <input type="text" onChange={(event) => this.setState({input: event.target.value})}/> <br/>
          <input type="submit" onSubmit={() => console.log(this.state.input)} />
        </form>
      </div>
    );
  }
}

export default App

但是,代码在 jsfiddle 中运行良好。

http://jsfiddle.net/swapnil95/k0jpruyu/2/

如有任何回复,我们将不胜感激。谢谢!!

以下应该有效:

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {input: undefined};
  }

  render() {
    return (
      <div className="App" marginTop="200px">
        <div className="App-header">
          <h2>Timestamp Microservice</h2>
        </div>
        <p className="App-intro">
          Converts a Unix timestamp (2365145258) to a natural language date (December 16, 2016) and vice versa.
        </p>
        <form onSubmit={e => { e.preventDefault(); console.log(this.state.input) }}>    
          <input type="text" onChange={(event) => this.setState({input: event.target.value})}/> <br/>
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

您甚至不需要表单标签。如果你有它,页面将重新加载,但你将值存储在输入的 onChange 事件的状态中。基本上所有按钮需要做的就是将值输出到控制台。

render() {
return (
  <div className="App">
    <div className="App-header">
      <h2>Timestamp Microservice</h2>
    </div>
    <p className="App-intro">
      Converts a Unix timestamp (2365145258) to a natural language date (December 16, 2016) and vice versa.
    </p>

      <input type="text" onChange={(event) => this.setState({input: event.target.value})}/> <br/>
      <button onClick={() => console.log(this.state.input)}> Submit </button>

  </div>
);

}