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

时间:2016-12-21 19:40:34

标签: reactjs event-handling jsfiddle

我对此代码的最终目标是,我希望在按下按钮时将输入到文本字段中的数据记录到控制台,但是在我的开发环境中不执行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/

非常感谢任何回复。谢谢!

2 个答案:

答案 0 :(得分:0)

以下应该有效:

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>
    );
  }
}

答案 1 :(得分:0)

您甚至不需要表单标签。如果你有它,页面将重新加载,但你将值存储在输入上的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>
);

}