在<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>

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


当前回答

我正在为语言选择器制作下拉菜单-但我需要下拉菜单在页面加载时显示当前语言。我要么从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的无价资源

其他回答

主点控制组件

您希望设置一个“受控组件”。这将要求您在元素上设置值,并处理on change事件以更新值。

https://reactjs.org/docs/forms.html#controlled-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 />

带有默认值的动态可重用示例

这将接受一个字符串集合,并将第一个字符串作为默认值。

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']}
/>
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>
   );
 }

}

简单地添加作为选择标签的第一个选项:

<option disabled hidden value=''></option>

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

使用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>
)
}