[英]Can't render react-select, only basic HTML select
我有一個<select>
元素,可以從Rails數據模型中提取選項。 可以,但是會產生沼澤標准的HTML選擇下拉列表。
但是,我想使用react-select組件,這就是我在努力的地方。 我可以呈現react-select下拉列表,但選項為空白。 我在控制台中沒有任何錯誤,並且我可以在React-Dev-Tools中看到陣列中的51個項目。
這是產生基本HTML下拉列表的代碼。
import React from 'react';
import axios from 'axios';
import Select from 'react-select';
class Country extends React.Component {
constructor(props) {
super(props)
this.state = {
countries: []
}
}
getCountries() {
axios.get(`/countries.json`)
.then(res => {
const countries = res.data;
this.setState({ countries });
})
.catch(error => console.log(error))
}
componentDidMount() {
this.getCountries()
}
render() {
return (
<div className="container">
<select className="taskList">
{this.state.countries.map((country) => {
return (
<option key={country.id} value={country.id}>{country.country_name}</option>
)
})}
</select>
</div>
)
}
}
export default Country
這是我正在嘗試進行react-select的代碼,並且不起作用
import React from 'react';
import axios from 'axios';
import Select from 'react-select';
class Country extends React.Component {
constructor(props) {
super(props)
this.state = {
countries: []
}
}
getCountries() {
axios.get(`/countries.json`)
.then(res => {
const countries = res.data;
this.setState({ countries });
})
.catch(error => console.log(error))
}
componentDidMount() {
this.getCountries()
}
render() {
return (
let countryItems = this.state.countries.map((country) =>
<option key={country.id} value={country.id}>{country.country_name}</option>
);
return (
<div className="container">
<label>Country</label>
<Select id="country" name="coffee_beans[country_id]" options={countryItems} />
</div>
)
}
}
export default Country
您的“反應選擇組件”選項應為對象數組:
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
現在,您正在傳遞一系列組件。 所以代替
let countryItems = this.state.countries.map((country) =>
<option key={country.id} value={country.id}>
{country.country_name} .
</option>
);
嘗試一下:
let countryItems = this.state.countries.map(country => ({
value: country.id,
label: country.country_name
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.