Lus*_*ney 6 javascript reactjs
所以我有这个问题,我想用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"
}
}
Run Code Online (Sandbox Code Playgroud)
我设置了对象的值"text"
用于在选择下拉列表中填充选项值,如下所示:
const securityModeOptions = Object.values(securityMode.select.options);
{securityModeOptions.map((mode, index) =>
<option key={index} value={mode.text}>
{mode.text}
</option>
)}
Run Code Online (Sandbox Code Playgroud)
我想要做的是,无论选择哪个选项值,它的相应值"description"
都会显示在div
旁边,并且div会根据选择的任何选项而改变.
谢谢!
您可以管理所选的状态key
,然后options
通过该对象从对象中获取相关条目key
.
像这样的东西:
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);
Run Code Online (Sandbox Code Playgroud)
<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"/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
525 次 |
最近记录: |