我在下拉列表中获得了正确的值,但之后当我调用 onchange 时,整个数组将作为参数传递。所以 e 具有整个数组,而不仅仅是所选的值 这是代码:
const { accountIDs } = this.state;
let accountIDlist =
accountIDs.length > 0 &&
accountIDs.map((item, i) => {
return (
<option key={i} value={item}>
{item}
</option>
);
}, this);
<Select
style={{ width: "100%" }}
defaultValue="123"
autosize={true}
onChange={e => {
debugger;
console.log(e);
this.reset();
this.setAccountID(e);
}}
>
<select value={accountIDlist}>{accountIDlist}</select>
</Select>
您的主要组件应该管理状态,因此加载 ids,并最初将
selected
设置为空。然后将 id 和选定状态传递给您的 Select
组件。这将迭代 id 以创建选项,如果选项的 id 与选择集的 id 匹配,则设置 selected
属性。
const { Component } = React;
class Select extends Component {
render() {
const { ids, selected, handleChange } = this.props;
return (
<select onChange={handleChange}>
<option selected>Choose</option>
{ids.map(id => {
return (
<option
value={id}
selected={selected === id}
>{id}
</option>
);
})}
</select>
);
}
}
class Example extends Component {
constructor(props) {
super();
this.state = { ids: props.ids, selected: '' };
}
handleChange = (e) => {
this.setState({ selected: +e.target.value });
}
render() {
const { ids, selected } = this.state;
return (
<Select
ids={ids}
selected={selected}
handleChange={this.handleChange}
/>
);
}
};
const ids = [1, 2, 3, 4, 5];
ReactDOM.render(
<Example ids={ids} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<select
name="account_id"
onChange={handleChange}
>
{props.accountIDList.map((accountId) => <option value={accountId}>{accountId}</option>)}
</select>
您可以在设置状态时设置默认值,如下所示...
const [accountId, setAccountId] = React.useState(account_id: 188619942792);
这个问题的答案是:
<Select
style={{ width: "100%" }}
defaultValue="188619942792"
autosize={true}
value = {accountIDlist}
onChange={e => {
this.reset()
this.setAccountID(e)
}}
>
{accountIDlist}
</Select >
这里不需要子选择组件。