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

在render()中,optionState从状态所有者传递给SortMenu组件。选项值作为道具从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

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

这样做可以避免语法错误,但显然不能解决问题:

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

<option value={option.value} selected={selected}>{option.label}</option>

我还试过这个:

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

<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>

有没有解决这个问题的推荐方法?


当前回答

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

在<select>上使用defaultValue或value道具,而不是在<option>上使用设置。

所以,你可以使用选项。在您选择的defaultValue上

其他回答

***Html:***
<div id="divContainer"></div>

var colors = [{ Name: 'Red' }, { Name: 'Green' }, { Name: 'Blue' }];
var selectedColor = 'Green';

ReactDOM.render(<Container></Container>, document.getElementById("divContainer"));

var Container = React.createClass({
    render: function () {
        return (
        <div>            
            <DropDown data={colors} Selected={selectedColor}></DropDown>
        </div>);
    }
});

***Option 1:***
var DropDown = React.createClass(
{
    render: function () {
        var items = this.props.data;
        return (
        <select value={this.props.Selected}>
            {
                items.map(function (item) {
                    return <option value={item.Name }>{item.Name}</option>;
                })
            }
        </select>);
    }
});

***Option 2:***
var DropDown = React.createClass(
{
    render: function () {
        var items = this.props.data;
        return (
        <select>
            {
                items.map(function (item) {
                    return <option value={item.Name} selected={selectedItem == item.Name}>{item.Name}</option>;
                })
            }
        </select>);
    }
});

***Option 3:***
var DropDown = React.createClass(
    {
        render: function () {
            var items = this.props.data;
            return (
            <select>
                {
                    items.map(function (item) {

                                            if (selectedItem == item.Name)
                    return <option value={item.Name } selected>{item.Name}</option>;
                else
                    return <option value={item.Name }>{item.Name}</option>;
                    })
                }
            </select>);
        }
    });
if you store objects in a state.

class Studentinformation extends Component
{
    constructor(props)
 {
   super(props);
   this.handlechange=this.handlechange.bind(this);
   this.handleSubmit=this.handleSubmit.bind(this);
   
   this.state={Studentinfo:{
          Name:'',
          Skill:'Java',
          Address:''
        }};
 }
 handlechange(event)
 {
   const name=event.target.name;
   const value=event.target.value;

   this.setState({ Studentinfo:
  {
    ...this.state.Studentinfo,
    [name]:[value]
  }});
 }
 handleSubmit(event)
 {
  event.preventDefault();
 }
 render(){
   return (
  <div>
    <form onSubmit={this.handleSubmit}>
      <label>Name: <input type="text" name="Name" value={this.state.Studentinfo.Name} onChange={this.handlechange}></input></label>
      <br/>
      <label>Skills: 
        <select value={this.state.Studentinfo.Skill} name="Skill" onChange={this.handlechange}>
          <option value="C++" >C++</option>
          <option value="C#">C#</option>
          <option  value="Java">Java</option>
        </select>
        </label>
        <br/>
        <textarea value={this.state.Studentinfo.Address} onChange={this.handlechange}/>
        <br/>
      <input type="submit" value="Submit"></input>
    </form>
  </div>
   );
 }

}

使用defaultValue预选Select的值。

<Select defaultValue={[{ value: category.published, label: 'Publish' }]} options={statusOptions} onChange={handleStatusChange} />

如果你使用无状态,那么

const IndexPage =({states, selectedState}) => {
return(
    <select id="states" defaultValue={selectedState} name="state">
{states.map(state=> (
                      <option value={state.id} key={state.id}>{state.name}</option>
                      ))
                      }
                    </select>
)
}

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

因为这整篇文章都在举水果的例子,所以我为你准备了各种水果的好处。

首先,用一个基本的React功能组件回答最初提出的问题——两个带和不带道具的示例,然后如何将组件导入到其他地方。 接下来,同样的例子-但与Typescript。 然后是一个额外的结局-使用Typescript的语言选择器下拉组件。


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

import React, { useState } from 'react'

export const FruitSelectDropdown = () => {
  const [currentFruit, setCurrentFruit] = useState('oranges')
  
  const changeFruit = (newFruit) => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

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

import React, { useState } from 'react'

export const FruitSelectDropdown = ({ fruitDetector }) => {
  const [currentFruit, setCurrentFruit] = useState(fruitDetector)
  
  const changeFruit = (newFruit) => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

然后在你的应用程序的其他地方导入FruitSelectDropdown

import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'

const App = () => {
  return (
    <div className="page-container">
      <h1 className="header">A webpage about fruit</h1>
      <div className="section-container">
        <h2>Pick your favorite fruit</h2>
        <FruitSelectDropdown fruitDetector='bananas' />

      </div>
    </div>
  )
}

export default App

带有Typescript的FruitSelectDropdown

import React, { FC, useState } from 'react'

type FruitProps = {
  fruitDetector: string;
}

export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
  const [currentFruit, setCurrentFruit] = useState(fruitDetector)
  
  const changeFruit = (newFruit: string): void => {
    setCurrentFruit(newFruit)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeFruit(event.target.value)}
        value={currentFruit}
      >
        <option value="apples">Red Apples</option>
        <option value="oranges">Outrageous Oranges</option>
        <option value="tomatoes">Technically a Fruit Tomatoes</option>
        <option value="bananas">Bodacious Bananas</option>
      </select>
    </form>
  )
}

然后在你的应用程序的其他地方导入FruitSelectDropdown

import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'

const App: FC = () => {
  return (
    <div className="page-container">
      <h1 className="header">A webpage about fruit</h1>
      <div className="section-container">
        <h2>Pick your favorite fruit</h2>
        <FruitSelectDropdown fruitDetector='bananas' />

      </div>
    </div>
  )
}

export default App

奖励轮:翻译下拉菜单与选定的当前值:

import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'

export const LanguageSelectDropdown: FC = () => {
  const { i18n } = useTranslation()
  const i18nLanguage = i18n.language
  const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
  
  const changeLanguage = (language: string): void => {
    i18n.changeLanguage(language)
    setCurrentI18nLanguage(language)
  }
  
  return (
    <form>
      <select 
        onChange={(event) => changeLanguage(event.target.value)}
        value={currentI18nLanguage}
      >
        <option value="en">English</option>
        <option value="de">Deutsch</option>
        <option value="es">Español</option>
        <option value="fr">Français</option>
      </select>
    </form>
  )
}

React/Typescript的无价资源