所以我想用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会根据选择的哪个选项而变化。
谢谢!
答案 0 :(得分:5)
您可以管理所选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);
<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"/>
答案 1 :(得分:3)
您可以保持所选选项的键处于状态,并显示此所选选项的description
。
示例
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 = {
options,
selected: Object.keys(options)[0]
};
onChange = event => {
this.setState({ selected: event.target.value });
};
render() {
const { options, selected } = this.state;
return (
<div>
<select onChange={this.onChange}>
{Object.keys(options).map(key => (
<option key={key} value={key}>
{options[key].text}
</option>
))}
</select>
<span>{options[selected].description}</span>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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"></div>