所以我对React还是比较新的。我想从三个表单输入中获取数据(并最终将其发布到数据库)。我一直在用互联网提供帮助,但我想在这里试试运气。就在这里,我试图只注意输入中的用户文本。
import React from 'react';
export default class AddForm extends React.Component {
constructor(props) {
super(props);
}
handlePlace(e) {
e.preventDefault();
const text = this.place.value.trim();
console.log(text);
}
handleDate(e) {
const text = this.date.value
console.log(text);
}
handleNotes(e) {
const text = this.notes.value
console.log(text);
}
render() {
return(
<form className="form">
<h4>Add a Memory</h4><br></br>
<p className="add-info">Keep track of all the fun and amazing places you
have been.</p>
<input type="text" name="place" placeholder="place" ref={input =>
this.place = input}></input><br></br>
<input placeholder="time" ref={input => this.date = input}></input><br>
</br>
<input className="notes" placeholder="notes" ref={input => this.notes =
input}></input><br></br>
<button className="save" type="button" onClick=
{this.handleSave}>Save</button>
</form>
);
}
handleSave() {
console.log(this.handlePlace)
console.log(this.handleDate)
console.log(this.handleNotes)
}
}
答案 0 :(得分:1)
虽然可以使用ref来执行此操作,但除非有必要,否则不建议实际触摸dom。我认为这会有所帮助 想想这个'反应方式'。
在React中,应用程序的状态驱动视图,包括输入。所以你应该做的是让状态填充输入的值,然后更新状态以改变那些输入中的内容。像这样:
export default class AddForm extends React.Component {
constructor(props) {
super(props);
//change here
this.handlePlace = this.handlePlace.bind(this);
this.handleDate = this.handleDate.bind(this);
this.handleNotes = this.handleNotes.bind(this);
this.handleSave = this.handleSave.bind(this);
this.state = {
placeText: '',
timeText: '',
noteText: '',
};
}
// all changed
handlePlace(e) {
this.setState({ placeText: e.target.value });
}
handleDate(e) {
this.setState({ dateText: e.target.value });
}
handleNotes(e) {
this.setState({ notesText: e.target.value});
}
render() {
return(
<form className="form">
<h4>Add a Memory</h4><br></br>
<p className="add-info">Keep track of all the fun and amazing places you
have been.</p>
// change here
<input type="text" name="place" placeholder="place" value={this.state.placeText} onChange={(e) => this.handlePlace(e)}></input><br></br>
// change here. e is implicitly passed to the onChange handler
<input type="text" placeholder="time" value={this.state.dateText} onChange={this.handleDate}></input><br>
</br>
//change here
<input className="notes" placeholder="notes" value={this.state.notesText} onChange={this.handleNotes}></input><br></br>
<button className="save" type="button" onClick=
{this.handleSave}>Save</button>
</form>
);
}
handleSave() {
console.log(this.state.placeText)
console.log(this.state.dateText)
console.log(this.state.notesText)
}
}
这看起来很乏味,但从长远来看,这种声明式的风格确实能够带来好处。通过您的应用程序跟踪数据流变得更加容易。