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

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会根据选择的任何选项而改变.

谢谢!

Sag*_*b.g 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);
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)