React JSX:在所选的<select>选项上选择"selected"

can*_*era 359 javascript reactjs

<select>菜单的React组件中,我需要selected在反映应用程序状态的选项上设置属性.

render(),optionState从状态所有者传递到SortMenu组件.选项值props从JSON 传入.

render: function() {
  var options = [],
      optionState = this.props.optionState;

  this.props.options.forEach(function(option) {
    var selected = (optionState === option.value) ? ' selected' : '';

    options.push(
      <option value={option.value}{selected}>{option.label}</option>
    );
  });

// pass {options} to the select menu jsx
Run Code Online (Sandbox Code Playgroud)

但是,这会在JSX编译时触发语法错误.

这样做可以消除语法错误,但显然无法解决问题:

var selected = (optionState === option.value) ? 'selected' : 'false';

<option value={option.value} selected={selected}>{option.label}</option>
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

var selected = (optionState === option.value) ? true : false;

<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>
Run Code Online (Sandbox Code Playgroud)

有没有推荐的解决方法?

Sop*_*ert 594

React自动为此目的理解布尔值,所以你可以简单地写(注意:不推荐)

<option value={option.value} selected={optionsState == option.value}>{option.label}</option>
Run Code Online (Sandbox Code Playgroud)

它会适当地输出'选中'.

但是,React让您更轻松.您可以(并且应该)简单地在select标记本身上写入,而不是selected在每个选项上定义:value={optionsState}

<select value={optionsState}>
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅React select标记文档.

  • 使用当前版本的React(0.9)设置选项上的选定属性根本不起作用.而是在select元素上设置value属性. (48认同)
  • @ user1924375你应该使用onChange事件`onChange = {this.handleSelect}`并为你的组件设置状态值,例如:'handleSelect:function(){this.setState({value:event.target.value});} `这将使用新选择的项目重新呈现您的选择组件.希望它会对你有所帮助. (5认同)
  • 而是使用`defaultValue`进行初始化 (3认同)
  • 尝试在 &lt;select&gt; 上使用 defaultValue,但请注意:当呈现 &lt;select&gt; 时,&lt;options&gt; 必须已经可用,否则它将无法工作。如果您在渲染 &lt;select&gt; 后异步加载选项,那么您可能必须在 &lt;option&gt; 上使用 selected={condition} 才能使其正常工作。或者,渲染一些其他控件(例如 Spinner),直到所有值都可用。 (3认同)
  • 我使用ajax.defaultValue加载数据对我不起作用.值正在工作,但我无法在选择列表上选择另一个项目.列表正在打开,但当我选择其中一个时,它选择值项目.任何想法? (2认同)

小智 64

当你尝试设置以下内容的"selected"属性时,你可以做React警告你的事情<option>:

使用defaultValuevalue道具上<select>,而不是设置selected<option>.

所以,你可以用options.valuedefaultValue你的选择中

  • 如果我仍想指出当前选择的选项,我该怎么做呢?我目前能够实际保持选项的唯一方法(并保持表单的状态以便将来POST)是通过设置select = true.我已经尝试设置select元素的defaultValue和value props,但是这不会在视图中通过在选项菜单中设置选择的正确选项来呈现.有什么建议? (9认同)
  • 例子可能?? (4认同)
  • 不适合我: &lt;select className="form-control" value="Mois"&gt; (2认同)

And*_*enz 17

这是一个完整的解决方案,其中包含最佳答案和下面的评论(这可能有助于某些人努力拼凑起来):

在主要组成部分:

class ReactMain extends React.Component {

  constructor(props) {
    super(props);
    this.state = { fruit: props.item.fruit };
  }

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  }

  saveItem = () => {
    const item = {};
    item.fruit = this.state.fruit;
    // do more with item object as required (e.g. save to database)
  }

  render() {
    return (
      <ReactExample name="fruit" value={this.state.fruit} handleChange={this.handleChange} />
    )
  }

}
Run Code Online (Sandbox Code Playgroud)

包含的组件(现在是无状态功能):

export const ReactExample = ({ name, value, handleChange }) => (
  <select name={name} value={value} onChange={handleChange}>
    <option value="A">Apple</option>
    <option value="B">Banana</option>
    <option value="C">Cranberry</option>
  </select>
)
Run Code Online (Sandbox Code Playgroud)

主要组件维护水果的选定值(处于状态),包含的组件显示select元素,更新被传递回主组件以更新其状态(然后循环回包含的组件以更改所选值).

请注意使用名称prop,它允许您为同一表单上的其他字段声明单个handleChange方法,而不管其类型如何.


tac*_*day 15

我正在为语言选择器制作一个下拉菜单 - 但我需要下拉菜单在页面加载时显示当前语言。我要么从 URL param 获取初始语言example.com?user_language=fr,要么从 user\xe2\x80\x99s 浏览器设置中检测它。然后,当用户与下拉列表交互时,所选语言将被更新,并且语言选择器下拉列表将显示当前选择的语言。

\n

由于整个帖子都给出了水果的例子,我为您提供了各种水果的好处。

\n
    \n
  • 首先,用基本的 React 功能组件回答最初提出的问题 - 两个带和不带 props 的示例,然后是如何在其他地方导入该组件。

    \n
  • \n
  • 接下来是相同的示例 - 但使用 Typescript 进行了增强。

    \n
  • \n
  • 然后是一个额外的结局 - 使用 Typescript 的语言选择器下拉组件。

    \n
  • \n
\n
\n

基本 React (16.13.1) 功能组件示例。两个例子FruitSelectDropdown,一个没有道具,一个有接受道具fruitDetector

\n
import React, { useState } from \'react\'\n\nexport const FruitSelectDropdown = () => {\n  const [currentFruit, setCurrentFruit] = useState(\'oranges\')\n  \n  const changeFruit = (newFruit) => {\n    setCurrentFruit(newFruit)\n  }\n  \n  return (\n    <form>\n      <select \n        onChange={(event) => changeFruit(event.target.value)}\n        value={currentFruit}\n      >\n        <option value="apples">Red Apples</option>\n        <option value="oranges">Outrageous Oranges</option>\n        <option value="tomatoes">Technically a Fruit Tomatoes</option>\n        <option value="bananas">Bodacious Bananas</option>\n      </select>\n    </form>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

或者你可以让 FruitSelectDropdown 接受 props,也许你有一个输出字符串的函数,你可以使用fruitDetectorprops传递它

\n
import React, { useState } from \'react\'\n\nexport const FruitSelectDropdown = ({ fruitDetector }) => {\n  const [currentFruit, setCurrentFruit] = useState(fruitDetector)\n  \n  const changeFruit = (newFruit) => {\n    setCurrentFruit(newFruit)\n  }\n  \n  return (\n    <form>\n      <select \n        onChange={(event) => changeFruit(event.target.value)}\n        value={currentFruit}\n      >\n        <option value="apples">Red Apples</option>\n        <option value="oranges">Outrageous Oranges</option>\n        <option value="tomatoes">Technically a Fruit Tomatoes</option>\n        <option value="bananas">Bodacious Bananas</option>\n      </select>\n    </form>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后导入FruitSelectDropdown应用程序中的其他位置

\n
import React from \'react\'\nimport { FruitSelectDropdown } from \'../path/to/FruitSelectDropdown\'\n\nconst App = () => {\n  return (\n    <div className="page-container">\n      <h1 className="header">A webpage about fruit</h1>\n      <div className="section-container">\n        <h2>Pick your favorite fruit</h2>\n        <FruitSelectDropdown fruitDetector=\'bananas\' />\n\n      </div>\n    </div>\n  )\n}\n\nexport default App\n
Run Code Online (Sandbox Code Playgroud)\n
\n

FruitSelectDropdown使用打字稿

\n
import React, { FC, useState } from \'react\'\n\ntype FruitProps = {\n  fruitDetector: string;\n}\n\nexport const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {\n  const [currentFruit, setCurrentFruit] = useState(fruitDetector)\n  \n  const changeFruit = (newFruit: string): void => {\n    setCurrentFruit(newFruit)\n  }\n  \n  return (\n    <form>\n      <select \n        onChange={(event) => changeFruit(event.target.value)}\n        value={currentFruit}\n      >\n        <option value="apples">Red Apples</option>\n        <option value="oranges">Outrageous Oranges</option>\n        <option value="tomatoes">Technically a Fruit Tomatoes</option>\n        <option value="bananas">Bodacious Bananas</option>\n      </select>\n    </form>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后导入FruitSelectDropdown应用程序中的其他位置

\n
import React, { FC } from \'react\'\nimport { FruitSelectDropdown } from \'../path/to/FruitSelectDropdown\'\n\nconst App: FC = () => {\n  return (\n    <div className="page-container">\n      <h1 className="header">A webpage about fruit</h1>\n      <div className="section-container">\n        <h2>Pick your favorite fruit</h2>\n        <FruitSelectDropdown fruitDetector=\'bananas\' />\n\n      </div>\n    </div>\n  )\n}\n\nexport default App\n
Run Code Online (Sandbox Code Playgroud)\n
\n

奖励回合:具有所选当前值的翻译下拉列表:

\n
import React, { FC, useState } from \'react\'\nimport { useTranslation } from \'react-i18next\'\n\nexport const LanguageSelectDropdown: FC = () => {\n  const { i18n } = useTranslation()\n  const i18nLanguage = i18n.language\n  const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)\n  \n  const changeLanguage = (language: string): void => {\n    i18n.changeLanguage(language)\n    setCurrentI18nLanguage(language)\n  }\n  \n  return (\n    <form>\n      <select \n        onChange={(event) => changeLanguage(event.target.value)}\n        value={currentI18nLanguage}\n      >\n        <option value="en">English</option>\n        <option value="de">Deutsch</option>\n        <option value="es">Espa\xc3\xb1ol</option>\n        <option value="fr">Fran\xc3\xa7ais</option>\n      </select>\n    </form>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

React/Typescript 的宝贵资源

\n


CTS*_*_AE 11

要点 - 受控组件

您正在寻求设置“受控组件”。这将要求您在元素上设置值并处理更改事件以更新值。

https://reactjs.org/docs/forms.html#control-components

例子

https://codepen.io/codyswartz/pen/QWqYNrY

简单功能组件选择示例

这还包括默认值并将其灰显。

const defaultSelectValue = "Select a fruit"

const SelectExample = () => {
  const [selected, setSelected] = useState(defaultSelectValue)

  return (
    <>
      <label htmlFor="fruits">Fruits</label>{' '}
      <select
        id="fruits"
        name="fruits"
        defaultValue={selected}
        style={{ color: selected === defaultSelectValue ? "gray" : "black" }}
        onChange={e => setSelected(e.target.value)}
      >
        <option>{defaultSelectValue}</option>
        <option>Banana</option>
        <option>Apple</option>
        <option>Orange</option>
      </select>

      <h2>Selected: {selected}</h2>
    </>
  )
}

// Usage
<SelectExample />
Run Code Online (Sandbox Code Playgroud)

默认情况下的动态可重用示例

这将采用第一个字符串作为默认值的字符串集合。

const SelectExample = ({ name, items }) => {
  const defaultSelectValue = items[0]
  const [selected, setSelected] = useState(defaultSelectValue)

  return (
    <>
      <label htmlFor={name}>{name}</label>{' '}
      <select
        id={name}
        name={name}
        defaultValue={selected}
        style={{ color: selected === defaultSelectValue ? "gray" : "black" }}
        onChange={e => setSelected(e.target.value)}
      >
        {items.map(item => (
          <option key={item} value={item}>
            {item}
          </option>
        ))}
      </select>

      <h2>Selected: {selected}</h2>
    </>
  )
}

// Usage
<SelectExample
  name="fruits"
  items={['Select a fruit', 'Banana', 'Apple', 'Orange']}
/>
Run Code Online (Sandbox Code Playgroud)


小智 5

只需添加为选择标签的第一个选项:

<option disabled hidden value=''></option>
Run Code Online (Sandbox Code Playgroud)

这将成为默认值,当您选择一个有效选项时,您的状态将被设置


Rah*_*mad 5

这是如何执行此操作的最新示例。从react docs以及自动绑定的“ fat-arrow”方法语法。

class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};
  }

  handleChange = (event) =>
    this.setState({value: event.target.value});

  handleSubmit = (event) => {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite flavor:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
} 
Run Code Online (Sandbox Code Playgroud)


sud*_*ang 5

使用 React 16.8。我们可以使用钩子来做到这一点,如下例所示

代码沙盒链接

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const options = [
    "Monty Python and the Holy Grail",
    "Monty Python's Life of Brian",
    "Monty Python's The Meaning of Life"
  ];
  const filmsByTati = [
    {
      id: 1,
      title: "Jour de fête",
      releasedYear: 1949
    },
    {
      id: 2,
      title: "Play time",
      releasedYear: 1967
    },
    {
      id: 3,
      releasedYear: 1958,
      title: "Mon Oncle"
    }
  ];
  const [selectedOption, setSelectedOption] = useState(options[0]);
  const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
  return (
    <div className="App">
      <h1>Select Example</h1>
      <select
        value={selectedOption}
        onChange={(e) => setSelectedOption(e.target.value)}
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedOption}</span>

      <select
        value={selectedTatiFilm}
        onChange={(e) =>
          setSelectedTatiFilm(
            filmsByTati.find(film => (film.id == e.target.value))
          )
        }
      >
        {filmsByTati.map((film) => (
          <option key={film.id} value={film.id}>
            {film.title}
          </option>
        ))}
      </select>
      <span>Selected option: {selectedTatiFilm.title}</span>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)