如何解决React JS - 如何在输入或按下时提交表单
我有一个简单的 React JS 应用程序,我想向其中添加搜索功能。我已经创建了搜索函数代码并添加了搜索组件(来自 Semantic-UI),它将搜索到的值传递给函数。
这是搜索组件。
<Search
onSearchChange={(e) => this.handleSearchChangeNew(e.target.value)}
/>
async handleSearchChangeNew (value) {
console.log("value in new search: " + value)
this.props.updateSearchString(value);
fetch(`api/license/search/${JSON.stringify(this.props.searchString)}`,{
credentials: 'include'})
.then(response => response.json())
.then(data => this.setState({
licenses: data,isLoading: false,licensePage: data.slice(this.state.begin,this.state.end)
}))
.catch(() => this.props.history.push('/'));
}
我之前已经组合了一个有点不雅的搜索功能,其中输入被键入到文本框中,并且通过按下“搜索”提交功能来调用上述搜索功能。该搜索功能将根据输入框中的内容重新填充页面。它仍然在那里,但我还添加了如上所示的新搜索功能代码。
作为参考,这里是整个班级。
import React,{ Component } from 'react';
import { Button,ButtonGroup,Container,Table } from 'reactstrap';
import { Pagination,Search } from 'semantic-ui-react'
import AppNavbar from './AppNavbar';
import { Link,withRouter } from 'react-router-dom';
import { instanceOf } from 'prop-types';
import { withCookies,Cookies } from 'react-cookie';
class LicenseList extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isrequired
};
constructor(props) {
super(props);
const {cookies} = props;
this.state = {
word: '',newWord: '',licenses: [],licensePage: [],csrftoken: cookies.get('XSRF-TOKEN'),isLoading: true,licensesPerPage: 7,activePage: 1,begin: 0,end: 7
};
this.remove = this.remove.bind(this);
this.btnClick = this.btnClick.bind(this);
this.handleSearchChangeNew = this.handleSearchChangeNew.bind(this);
}
componentDidMount() {
this.setState({isLoading: true});
console.log("searchString: " + this.props.searchString);
fetch(`/api/license/search/${this.props.searchString}`,{credentials: 'include'})
.then(response => response.json())
.then(data => this.setState({
licenses: data,this.state.end)
}))
.catch(() => this.props.history.push('/'));
}
async handleSearchChange(value) {
this.props.updateSearchString(value)
}
async searchFromString () {
this.setState({isLoading: true});
fetch(`api/license/search/${this.props.searchString}`,this.state.end)
}))
.catch(() => this.props.history.push('/'));
}
async clearSearchString(value) {
this.props.updateSearchString('');
}
async btnClick(
event: React.MouseEvent<HTMLAnchorElement>,data: PaginationProps
) {
await this.setState({activePage: data.activePage});
await this.setState({begin: this.state.activePage * this.state.licensesPerPage - this.state.licensesPerPage});
await this.setState({end: this.state.activePage *this.state.licensesPerPage});
this.setState({
licensePage: this.state.licenses.slice(this.state.begin,this.state.end),});
}
async remove(id) {
if (window.confirm('Are you sure you wish to delete this license?')) {
await fetch(`/api/license/${id}`,{
method: 'DELETE',headers: {
'X-XSRF-TOKEN': this.state.csrftoken,'Accept': 'application/json','Content-Type': 'application/json'
},credentials: 'include'
}).then(() => {
let updatedLicenses = [...this.state.licenses].filter(i => i.id !== id);
this.setState({licenses: updatedLicenses});
});
}
}
download(url) {
// fake server request,getting the file url as response
setTimeout(() => {
const response = {
file: url,};
// server sent the url to the file!
// Now,let's download:
window.open(response.file);
// you Could also do:
// window.location.href = response.file;
},100);
}
async handleSearchChangeNewx(value) {
this.props.updateSearchString(value);
}
async handleSearchChangeNew (value) {
console.log("value in new search: " + value)
this.props.updateSearchString(value);
fetch(`api/license/search/${JSON.stringify(this.props.searchString)}`,this.state.end)
}))
.catch(() => this.props.history.push('/'));
}
render() {
const {licensePage,activePage } = this.state;
const {licenses,isLoading,licensesPerPage} = this.state;
const totalPages = Math.ceil(licenses.length / licensesPerPage);
if (isLoading) {
return <p>Loading...</p>;
}
const licenseList = licensePage.map(license => {
return<tr key={license.id}>
<td style={{whiteSpace: 'Nowrap'}}>{license.fullName}</td>
<td style={{whiteSpace: 'Nowrap'}}>{license.requester}</td>
<td style={{whiteSpace: 'Nowrap'}}>{license.tag}</td>
<td style={{whiteSpace: 'Nowrap'}}>{license.dateCreated.substring(0,10)}</td>
<td style={{whiteSpace: 'Nowrap'}}>{license.expiration}</td>
<td style={{whiteSpace: 'Nowrap'}}>{license.systems}</td>
<td>
<ButtonGroup>
<Button size="sm" color="primary" tag={Link} to={"/licenses/" + license.id}>Edit</Button>
<Button size="sm" color="dark" onClick={() => this.download(license.url)}>Download</Button>
<Button size="sm" color="danger" onClick={() => this.remove(license.id)}>Delete</Button>
</ButtonGroup>
</td>
</tr>
});
return (
<div>
<AppNavbar/>
<Container fluid>
<h3>License List</h3>
<div className="float-left">
<div>
<input type="text" value={this.props.searchString} onChange={(e) => this.props.updateSearchString(e.target.value)} />
<input type="submit" value="Search" onClick={() => this.searchFromString()} />
<input type="submit" value="Clear Search" onClick={() => this.clearSearchString()} />
<Search
onSearchChange={(e) => this.handleSearchChangeNew(e.target.value)}
/>
</div>
</div>
<div className="float-right">
<Button color="primary" tag={Link} to="/licenses/new">Create License</Button>
</div>
<Table className="mt-4">
<thead>
<tr>
<th width="10%">Full Name</th>
<th width="5%">Requester</th>
<th width="10%">Tag</th>
<th width="5%">Created</th>
<th width="5%">Expiration</th>
<th width="5%">Systems</th>
<th width="10%">Actions</th>
</tr>
</thead>
<tbody>
{licenseList}
</tbody>
</Table>
<div>
</div>
<div className="col text-center">
<Pagination
activePage={activePage}
onPageChange={this.btnClick}
totalPages={totalPages}
ellipsisItem={null}
/>
</div>
</Container>
</div>
);
}
}
export default withCookies(withRouter(LicenseList));
解决方法
使用原生 <form>
元素,一切顺利!浏览器将完成艰巨的任务。将您的输入包装在 <form>
而不是 <div>
中,并将您的实际表单提交处理程序传递给 onSubmit
上的 <form onSubmit={this.handleSearchChangeNew}>
侦听器。那么你需要一个 event.preventDefault()
来防止页面刷新;不过,给你的输入一个 name
也是一个好习惯。 <form>
元素将做一个基本的验证,并处理回车键;
同时,如果您对使用 <form>
感到不舒服,您也可以自己处理键更改事件(就像您处理大多数原生 <form>
功能一样);
在表单逻辑所在的父 html 元素上添加 keyDown
事件侦听器;然后处理 enter
key code。
function (event) {
if (event.which == 13 || event.keyCode == 13) {
// enter key had been pressed
// submit
}
};
编辑:如何手动处理keydown:
<div onKeyDown={(e)=>console.log(e.keyCode)}>
<input .... />
<input .... />
<Search onSearchChange={(e) => this.handleSearchChangeNew(e.target.value)} />
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。