我正在尝试使用第一个值(来自options参数)填充一个语义UI反应下拉列表。但我无法做到这一点。该下拉列表的值是我从后端获取的,然后将其映射到语义UI响应选择支持的格式。
我们将不胜感激。
//state object
this.state = {
users: [] ,
selectedUser: '',
defaultUser: string
}
//fetch call to get the values and then transforming
async componentDidMount()
{
try {
let data = await fetch('/api/fetch/users')
let users = await data.json();
users = users.map((obj:any) => ({ //formatting the list to support options array of semnatic-ui-react select
key: obj.id,
text: obj.name,
value: obj.name
}));
this.setState({users},defaultUser: users[0].value); //setting the dropdown with first value, but it is not happening
}
catch(e){
console.log('Error', e.message);
}
}
//onchange handler
dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
this.setState(prevState => ({
[data.name]: data.value
}));
}
//Inside render, Select
<Select
options={this.state.users}
name="selectedUser"
value={this.state.selectedUser}
onChange={this.dropdownChange}
defaultValue = {this.state.defaultUser}
/>
答案 0 :(得分:1)
我认为您不需要defaultValue属性。您可以在下面查看密码和框。我使用了react hooks,但是您明白了。
https://codesandbox.io/s/heuristic-wiles-eq7su
针对您的特定代码:
import React from "react";
import ReactDOM from "react-dom";
import { Select } from "semantic-ui-react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
selectedUser: ""
};
}
async componentDidMount(){
try {
let data = await fetch('/api/fetch/users')
let users = await data.json();
users = users.map((obj:any) => ({
key: obj.id,
text: obj.name,
value: obj.name
}));
this.setState({users}, () => {
this.setState({selectedUser: this.state.users[0].value});
})
}
//onchange handler
dropdownChange = (event, data) => {
this.setState({ selectedUser: data.value });
};
render() {
return (
<Select
onChange={this.dropdownChange}
placeholder="Select a user"
value={this.state.selectedUser}
selection
options={this.state.users}
/>
);
}
}