2 回答
TA贡献1848条经验 获得超6个赞
您可以用来state跟踪代码数组中选定的对象,因此您可以同时拥有BusinessCode和IndustryName
尽可能避免在 React 中使用 jQuery。检查下面的代码:
const businessCodes = [{
BusinessCode: 111,
IndustryName: "Crop Production"
},
{
BusinessCode: 112,
IndustryName: "Animal Production and Aquaculture"
},
{
BusinessCode: 113,
IndustryName: "Forestry and Logging"
}];
const codesList = () => {
return businessCodes.map((code, index) => {
return <option key={code.BusinessCode}>{code.IndustryName}</option>;
});
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {selectedOption: {}};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let selectedOption;
let filtered = businessCodes.filter(item => item["IndustryName"] === event.target.value)
if(filtered.length) selectedOption = filtered[0]
else selectedOption = {}
this.setState({selectedOption}, function(){
if(Object.keys(this.state.selectedOption).length)
console.log(this.state.selectedOption)
});
}
render() {
return (
<div>
<input
type="text"
placeholder="Enter Business Code"
list="code-dataList"
autoComplete="off"
value={this.state.value}
onChange={this.handleChange}
/>
{/* DATALISTS CODES*/}
<datalist id="code-dataList">
{codesList()}
</datalist>
</div>
);
}
}
// Render it
ReactDOM.render(
<App />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
TA贡献1848条经验 获得超2个赞
实际上,您错误地使用了它,并且从未尝试像 React 中的 getElementById("business-code") 那样访问 DOM。这是一种不好的做法,并且总是通过 onChange 事件获取价值。
使用值代替键,问题就解决了。
{this.state.businessCodes.map((code, index) => (
<option key={index} value={code.BusinessCode}>
{code.IndustryName}
</option>
))}
完整代码它是如何在 React 上工作的。
import React, { Component } from "react";
class App extends Component {
state = {
businessCodes: [
{
BusinessCode: 111,
IndustryName: "Crop Production"
},
{
BusinessCode: 112,
IndustryName: "Animal Production and Aquaculture"
},
{
BusinessCode: 113,
IndustryName: "Forestry and Logging"
}
]
};
render() {
return (
<div>
<input
type="text"
name="code"
className="filter-select-form-control"
placeholder="Enter Business Code"
id="business-code"
list="code-dataList"
autoComplete="off"
/>
<datalist id="code-dataList">
{this.state.businessCodes.map((code, index) => (
<option key={index} value={code.BusinessCode}>
{code.IndustryName}
</option>
))}
</datalist>
</div>
);
}
}
export default App;
- 2 回答
- 0 关注
- 137 浏览
添加回答
举报