我正在学习React。我正在尝试在输入框中选择国家/地区值,handlechange事件将以国家/地区代码为目标,并且值将自动选择。我没有在此处添加功能handlechange和handleClick,因为它们无法正常工作。我也为每个字段输入不同的输入框。如何只获得一个带有下拉列表的输入框?
export default class Api extends Component {
constructor(props) {
super(props);
this.state = {
country: [],
countryCode:''
};
}
componentDidMount() {
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => {
console.log(result);
console.warn(result);
this.setState({ country: result });
console.log("i am in console");
});
}
this.handleClick = this.handleClick.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
render() {
return (
<div>
<h1 className="text-center"> Api</h1>
<h2> country details</h2>
<div>
{this.state.country.map((countries, i) => (
<div key={i}>
<label>Select Country</label>
<select>
<option onClick={this.handleClick}> {countries.name}</option>
</select>
<label>Country Code: </label><input type="text" className="m-5" value={countries.callingCodes} onChange={this.handleInputChange} />
</div>
))}
</div>
</div>
);
}
}
您可以在这里试用我的更改。
import React, { Component } from "react";
export default class Api extends Component {
state = {
countries: [],
countryName: "",
countryCode: ""
};
handleCountryPick = (event) => {
event.preventDefault();
const country = this.state.countries.find(
(country) => country.name === event.target.value
);
this.setState({
countryCode: country.callingCodes,
countryName: country.name
});
};
async componentDidMount() {
const response = await fetch("https://restcountries.eu/rest/v2/all");
const countries = await response.json();
this.setState({ countries: countries });
}
render() {
return (
<div>
<h1 className="text-center">Api</h1>
<h2>country details</h2>
<CountrySelector
countries={this.state.countries}
countryName={this.state.countryName}
onCountryPickHandler={this.handleCountryPick}
/>
<CountryCodeInput countryCode={this.state.countryCode} />
</div>
);
}
}
const CountrySelector = ({ countryName, countries, onCountryPickHandler }) => {
const options = countries.map((country) => (
<option key={country.name} value={country.name}>
{country.name}
</option>
));
return (
<div>
<select value={countryName || "none"} onChange={onCountryPickHandler}>
{options}
<option value="none">None</option>
</select>
</div>
);
};
const CountryCodeInput = ({ countryCode }) => {
return (
<div>
<label>Country Code: </label>
<input type="text" value={countryCode} />
</div>
);
};
这是您需要学习才能从头开始实现的内容:
handleCountryPick
在保持状态的父countries
,countryName
,countryCode
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句