简体   繁体   English

根据浏览器语言 ReactJS 设置下拉值?

[英]Set Dropdown value based on Browser Language ReactJS?

So i have a small setup in which i have a dropdown and the Dropdown has two values.所以我有一个小的设置,其中我有一个下拉列表,并且下拉列表有两个值。 I am trying to set the default value of the dropdown based on the browser language detected.我正在尝试根据检测到的浏览器语言设置下拉列表的默认值。 So if the Browser language is English, the dropdown and it's value should default to English and if the Language is Spanish then it should default to Spanish and so on.因此,如果浏览器语言为英语,则下拉列表及其值应默认为English ,如果语言为Spanish ,则应默认为西班牙语,依此类推。 Essentially it should be dynamic and it might grow more into the Future.从本质上讲,它应该是动态的,并且可能会在未来发展得更多。 Any help will be Appreciated.任何帮助将不胜感激。

Check out this CodeSandbox for a working example.查看此CodeSandbox以获取工作示例。

This is the complete Code这是完整的代码

import React, { Component } from "react";

class Newbie extends Component {
  state = {
    languageSelection: [
      { option: "English", value: "en-us" },
      { option: "Spanish", value: "es" }
    ]
  };
  componentDidMount() {
    let detectedLanguage = navigator.language || navigator.userLanguage;
    alert("The Language is " + detectedLanguage)
  }

  render() {
    return (
      <div>
        <label>
          Language
          <select>
            <option value="en-us">English</option>
            <option value="es">Spanish</option>
          </select>
        </label>
      </div>
    );
  }
}

export default Newbie;

Thank you for all the assistance guys.: Much appreciated.谢谢大家的帮助。:非常感谢。 :) :)

import React, { Component } from "react";

class Newbie extends Component {
  state = { selected: navigator.language || navigator.userLanguage };

  handleChange = (e) => {
    this.setState({ selected: e.target.value })
  }


  render() {
    return (
      <div>
        <label>
          Language
          <select value={this.state.selected} onChange={this.handleChange}>
            <option value="en-US">English</option>
            <option value="es">Spanish</option>
          </select>
        </label>
      </div>
    );
  }
}

export default Newbie;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM