gpt4 book ai didi

javascript - 根据选择选项显示对象的值文本

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:24 25 4
gpt4 key购买 nike

所以我想用 React 解决这个问题。

假设我有一个这样的对象:

"options": {
"open": {
"text": "Open (Risky)",
"description": "Filler text for open"
},

"wpa": {
"text": "WPAWPA2PSK (TKIP / AES)",
"description": "Filler text for wpa"
},

"wpa2": {
"text": "WPA2-PSK (AES) (Recommended)",
"description": "Filler text for wpa2"
}
}

我设置了对象的值的 "text" 用于填充选择下拉列表中的选项值,如下所示:

const securityModeOptions = Object.values(securityMode.select.options);

{securityModeOptions.map((mode, index) =>
<option key={index} value={mode.text}>
{mode.text}
</option>
)}

我想做的是,无论选择哪个选项值,它对应的 "description" 都会显示在它旁边的 div 中,div 会根据无论选择哪个选项。

谢谢!

最佳答案

您可以管理所选key 的状态,然后通过keyoptions 对象中获取相关条目。

是这样的:

const options = {
open: {
text: "Open (Risky)",
description: "Filler text for open"
},

wpa: {
text: "WPAWPA2PSK (TKIP / AES)",
description: "Filler text for wpa"
},

wpa2: {
text: "WPA2-PSK (AES) (Recommended)",
description: "Filler text for wpa2"
}
};

class App extends React.Component {
state = { selectedOptionKey: "" };
onChange = ({ target }) => {
this.setState({ selectedOptionKey: target.value });
};
render() {
const { selectedOptionKey } = this.state;
const description =
options[selectedOptionKey] && options[selectedOptionKey].description;
return (
<div>
<select onChange={this.onChange}>
<option>Choose</option>
{Object.entries(options).map(([key, value]) => (
<option value={key}>{value.text}</option>
))}
</select>
<div>{description}</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>

关于javascript - 根据选择选项显示对象的值文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com