我是在反应js中开发应用程序的新手,我很困惑哪一个是使用表单的最佳方法/最佳实践,并且在控制/非受控方法之外的反应js中验证表单。任何指导对我都非常有帮助,请提前感谢。
答案 0 :(得分:0)
如果使用redux-form,表单验证和处理表单值将变得更加容易。
答案 1 :(得分:0)
这是一个示例反应注册表单,您将能够获得一个想法
<强> Home.jsx 强>
'use strict';
import React, {Component} from 'react';
import AddBook from './AddBook';
import axios from 'axios';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
books:[],
authors:[]
};
this.addBook = this.addBook.bind(this);
}
componentWillMount(){
axios.get(`http://localhost:8095/authors`)
.then(res=>{
const authors=res.data;
this.setState({authors});
console.log(res);
})
}
addBook(Name,ISBN,Author,Price,Year,Publisher){
axios.post(`http://localhost:8095/books`,{
Name:Name,
ISBN:ISBN,
Author:Author,
Price:Price,
Year:Year,
Publisher:Publisher
}).then(res=>{
console.log(res);
})
}
render() {
return <div>
<AddBook
addBook={this.addBook}
authors={this.state.authors}
/>
</div>
}
}
<强> AddBook.jsx 强>
'use strict';
import React, {Component} from 'react';
import { Button } from 'react-bootstrap';
export default class AddBook extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event){
event.preventDefault();
this.props.addBook(
this.nameInput.value,
this.ISBNInput.value,
this.AuthorInput.value,
this.PriceInput.value,
this.YearInput.value,
this.PublisherInput.value
);
this.nameInput.value='';
this.ISBNInput.value='';
this.AuthorInput.value='';
this.PriceInput.value='';
this.YearInput.value='';
this.PublisherInput.value='';
}
render() {
return <div>
<form>
<header>Add Books</header>
<div><input placeholder="Name" ref={nameInput=>this.nameInput=nameInput}/></div>
<div><input placeholder="ISBN" ref={ISBNInput=>this.ISBNInput=ISBNInput}/></div>
<div><select ref={AuthorInput=>this.AuthorInput=AuthorInput}>
<option selected disabled >--author name--</option>
{
this.props.authors.map(author=>
<option key={author._id}>{author.fname}</option>
)
}
</select>
</div>
<div><input placeholder="Price" ref={PriceInput=>this.PriceInput=PriceInput}/></div>
<div><input placeholder="Year" ref={YearInput=>this.YearInput=YearInput}/></div>
<div><input placeholder="Publisher" ref={PublisherInput=>this.PublisherInput=PublisherInput}/></div>
<div><Button onClick={this.onSubmit}>Add Book</Button></div>
</form>
</div>
}
}
<强> View.jsx 强>
'use strict';
import React, {Component} from 'react';
import axios from 'axios';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
books:[]
};
}
componentWillMount(){
axios.get(`http://localhost:8095/books`).then(res=>{
const books=res.data;
this.setState({books});
console.log(books);
})
}
render() {
return <div>
<h2>This is the available book list</h2>
<div>
{
this.state.books.map(book =>
<div>
<span key={book._id}>Name:{book.Name}</span>
</div>
)
}
</div>
</div>
}
}
我也是React的新手,因此代码中可能存在冗余。但这样可以正常工作。希望这会有所帮助。