我正在使用React-Bootstrap FormControl下拉列表。在这个DD我应用了map函数,它迭代并提供下拉选项。
我没有得到如何设置所选选项的值。我尝试使用onChange
和onSelect
。在更改时,我调用了以下代码行:
下面是使用React-Bootstrap在Reactjs中使用的drop的简单示例:
export default class SignUp extends Component {
构造函数(props,context){ 超级(道具,背景);
this.handleChange = this.handleChange.bind(this);
this.register =this.register.bind(this);
this.handleChangeDate = this.handleChangeDate.bind(this);
this.state = {
gender:'',
genderCat: [],
}
handleChangeGender(){
const name = e.target.name;
const value = e.target.value;
console.log(name, value);
this.setState({[name]: value});
console.log(this.state);
}
componentDidMount() {
api to get gender => GetData('getGender').then( (result) => {
this.setState({
genderCat: result
});
// this.state.data = result.message_text;
// console.log(data.message_text);
})
render() {
<FormControl
name="gender"
componentClass="select"
placeholder="select"
onChange={this.handleChangeGender}
>
{
this.state.genderCat.map((data) =>
<option key={data.id} value={data.value} >
{data.name}</option>
)
}
<FormControl.Feedback />
</FormControl>
}
}
如何设置状态值?我比状态值落后一步。如果我选择Male(来自map函数,它的值为1),那么就是第一次。然后在状态中给它null,但是然后onchange女性它取1,现在如果我改为另外它需要2(它的女性价值)
答案 0 :(得分:2)
我不知道你为什么不能这样做但是这里有一个工作的例子来自文档,没有经过验证和稍微改变:
import React from "react";
import { FormGroup, ControlLabel, FormControl } from "react-bootstrap";
const genderList = [
{ id: 1, name: "male" },
{ id: 2, name: "female" },
{ id: 3, name: "other" }
];
// mimicing API request
const getGender = () =>
new Promise(resolve =>
setTimeout(() => {
resolve(genderList);
}, 1000)
);
class FormExample extends React.Component {
state = {
gender: "",
genderCat: []
};
componentDidMount() {
getGender().then(data =>
this.setState({ genderCat: data, gender: data[ 0 ].name }));
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
createOptions = () =>
this.state.genderCat.length
? this.state.genderCat.map(data => (
<option key={data.id} value={data.name}>
{data.name}
</option>
))
: "";
render() {
return (
<form>
<p>
Selected gender: <strong>{this.state.gender}</strong>
</p>
<FormGroup controlId="formControlsSelect">
<ControlLabel>Select</ControlLabel>
<FormControl
name="gender"
componentClass="select"
onChange={this.handleChange}
>
{this.createOptions()}
</FormControl>
</FormGroup>
</form>
);
}
}
export default FormExample;