我使用此代码的最终目标是,我希望将数据输入到文本字段中时,在按下按钮时将数据登录到控制台,但是我的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/
任何回应都将不胜感激。谢谢!
您甚至不需要表单标签。如果有的话,页面将重新加载,但是您正在使用输入上的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>
);
}
以下应该有效:
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>
);
}
}