我有一个项目,用户可以在其中输入一些输入,然后将数据推送到mongDB实例。然后,我有一个搜索栏,用户可以在其中搜索数据,一旦他们单击选定的ID,便会将所有相应的文档信息放入一些文本字段中,以供用户查看。
我的问题是选择一个项目部件,如果用户单击ID填充字段,它会起作用。但是我将它们放在H1标签中进行测试,并且它将为每个ID显示一个H1。
现在,我将其移至选择字段中,出现此消息。
我只需要将每个ID都显示在一个选择框中,而不是为每个ID重新呈现一个框
这是我当前的代码:
import React from "react";
import PropTypes from "prop-types";
import { Form, FormGroup, Input, Container, Row, Col, Label } from "reactstrap";
import "./Search.css";
import axios from "axios";
import SearchBox from "react-search-box";
class Search extends React.Component {
static propTypes = {
handleCustomer: PropTypes.func.isRequired
};
constructor(props) {
super(props);
this.state = {
searchInfo: [],
query: "",
companyFilter: ""
};
this.itWorks = this.itWorks.bind(this);
this.handleSearch = this.handleSearch.bind(this);
}
search = query => {
let filter = {};
if (this.state.companyFilter) {
filter = {
customerID: {
$regex: ".*" + this.state.companyFilter + ".*",
$options: "i"
}
};
}
let url = "http://localhost:5000/getData?filter=" + JSON.stringify(filter);
axios.get(url).then(res => {
const searchInfo = (res.data || []).map(obj => ({
customerID: obj.customerID,
company: obj.companyName,
sinage: obj.sinageCodes,
curtain: obj.curtainCodes,
method: obj.Method,
notes: obj.Notes
}));
this.setState({ searchInfo });
console.log(searchInfo);
});
};
itWorks() {
this.setState({
companyFilter: document.getElementById("exampleSearch").value
});
}
handleSearch = e => {
if (e.key === "Enter") {
this.search();
}
};
componentDidMount() {
this.search("");
}
render() {
const { query, searchInfo } = this.state;
return (
<div>
<Container>
<FormGroup>
<Label for="exampleSearch" />
<Input
type="search"
name="search"
id="exampleSearch"
placeholder="Search for a CumstomerID"
onChange={this.itWorks}
onKeyPress={this.handleSearch}
/>
</FormGroup>
</Container>
{this.state.searchInfo.map(function(searchInfo, index) {
return (
<FormGroup>
<Label for="exampleSelectMulti">Select customerID</Label>
<Input
onChange={this.state.value}
onClick={() => this.props.handleCustomer(searchInfo)}
type="select"
name="selectMulti"
id="exampleSelectMulti"
multiple
>
<option key={index}>
{" "}
{searchInfo.customerID.match(
new RegExp(this.state.companyFilter, "i")
) || this.state.companyFilter === ""
? "customerID: " + searchInfo.customerID
: ""}
</option>
</Input>
</FormGroup>
);
}, this)}
</div>
);
}
}
export default Search;
Search函数工作正常,仅需从我的API中获取所有返回的数据以在一个选择框中显示即可。
谢谢!
答案 0 :(得分:0)
您可能希望映射选项。像这样的东西。
<FormGroup>
<Label for="exampleSelectMulti">Select customerID</Label>
<Input
onChange={this.handleChange}
type="select"
name="selectMulti"
id="exampleSelectMulti"
value={this.state.value}
multiple
>
{this.state.searchInfo.map(function(searchInfo, index) {
<option key={index}>
{" "}
{searchInfo.customerID.match(
new RegExp(this.state.companyFilter, "i")
) || this.state.companyFilter === ""
? "customerID: " + searchInfo.customerID
: ""}
</option>
</Input>
</FormGroup>