我有一个带有选择元素的表单。选择元素的选项值来自 API。所以,我必须动态创建选项。但是,我无法从中获取选择元素DOM
。
以下是尝试过的代码。我尝试使用 访问选择 ID 元素findDOMNode
。这些都没有得到元素。
我需要做什么才能选择元素?
componentDidMount() {
companyUserNames()
.then(result => {
const companyUsername = result;
console.log(result);
//output ==> [ { userName: "ABC",fullName: "ABC XYZ"}, {userName:
// "DEF",fullName: "DEF QRW"}]
companyUsername.forEach(role => {
console.log(role);
const roledynamic1 = document.getElementById("name1");
console.log(roledynamic3);
//output = null
const roledynamic2 = this.refs.name1
console.log(roledynamic3);
//output = undefiend
const roledynamic3 = ReactDOM.findDOMNode(this.refs.name1)
console.log(roledynamic3);
//output = null
const newchild1 = document.createElement("option");
newchild1.value = role.userName;
newchild1.text = role.fullName;
roledynamic3.add(newchild1);
});
})
.catch(error => {
console.log(error);
});
}
render(){
return(
<form>
//some input field
<div className='select'>
<select
name='userName'
id='name1'
ref="name1"
className='input common-input-style'
maxLength='255'
value={this.state.userName.value}
onChange={this.handleInputChange}
>
<option>Name</option>
</select>
</div>
//some input field
<form/>
)
}