Javascript React JSX:选择";精选;关于选定的<;选择>;选项

Javascript React JSX:选择";精选;关于选定的<;选择>;选项,javascript,reactjs,Javascript,Reactjs,在菜单的React组件中,我需要在反映应用程序状态的选项上设置selected属性 在render()中,将选项state从状态所有者传递到SortMenu组件。选项值从JSON以props的形式传入 render: function() { var options = [], optionState = this.props.optionState; this.props.options.forEach(function(option) { var selecte

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

render()
中,将
选项state
从状态所有者传递到SortMenu组件。选项值从JSON以
props
的形式传入

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
render:function(){
var选项=[],
optionState=this.props.optionState;
this.props.options.forEach(函数(选项){
选择的变量=(optionState===option.value)?“选择的”:“;
选项。推(
{option.label}
);
});
//将{options}传递到选择菜单jsx
但是,这会在JSX编译时触发语法错误

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

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

<option value={option.value} selected={selected}>{option.label}</option>
var selected=(optionState==option.value)?“selected”:“false”;
{option.label}
我也试过:

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

<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>
var selected=(optionState==option.value)?true:false;
{option.label}

有推荐的解决方法吗?

React让您更容易做到这一点。您可以(而且应该)简单地在select标记本身上写入
value={optionState}
,而不是在每个选项上定义
selected

<select value={optionsState}>
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

苹果
香蕉
蔓越莓
有关详细信息,请参阅

此外,React为此自动理解布尔值,因此您只需编写(注意:不推荐)

{option.label}

并且它将适当地输出“selected”。

当您试图设置
的“selected”属性时,可以执行React警告您的操作:

使用
上的
默认值
道具,而不是在
上设置所选的


因此,您可以在选择的
默认值
上使用
选项.value
,当状态更改时,
标记未更新为正确的
我遇到了一个问题。我的问题似乎是,如果您快速连续渲染两次,第一次没有预先选择
,而是第二次使用一个,则
标记不会在第二次渲染时更新,而是保持在默认的第一次渲染上

我使用找到了一个解决方案。您需要获取对
标记节点(可能嵌套在某些组件中)的引用,然后在
组件diddupdate
钩子中手动更新其上的
属性

componentDidUpdate(){
  let selectNode = React.findDOMNode(this.refs.selectingComponent.refs.selectTag);
  selectNode.value = this.state.someValue;
}
***Html:***
var colors=[{Name:'Red'},{Name:'Green'},{Name:'Blue'}];
var selectedColor='绿色';
render(,document.getElementById(“divContainer”);
var Container=React.createClass({
渲染:函数(){
返回(
);
}
});
***备选案文1:***
var DropDown=React.createClass(
{
渲染:函数(){
var items=this.props.data;
返回(
{
items.map(功能(项目){
返回{item.Name};
})
}
);
}
});
***备选案文2:***
var DropDown=React.createClass(
{
渲染:函数(){
var items=this.props.data;
返回(
{
items.map(功能(项目){
返回{item.Name};
})
}
);
}
});
***备选案文3:***
var DropDown=React.createClass(
{
渲染:函数(){
var items=this.props.data;
返回(
{
items.map(功能(项目){
if(selectedItem==item.Name)
返回{item.Name};
其他的
返回{item.Name};
})
}
);
}
});

为MULTISELECT/OptGroup发布了类似的答案:

render() {
  return(
    <div>
      <select defaultValue="1" onChange={(e) => this.props.changeHandler(e.target.value) }>
        <option disabled="disabled" value="1" hidden="hidden">-- Select --</option>
        <optgroup label="Group 1">
          {options1}
        </optgroup>
        <optgroup label="Group 2">
          {options2}
        </optgroup>
      </select>
    </div>
  )
}
render(){
返回(
this.props.changeHandler(e.target.value)}>
--挑选--
{options1}
{options2}
)
}

以下是一个完整的解决方案,其中包含了最佳答案和下面的注释(这可能有助于努力拼凑答案的人):

ES6更新(2019)-使用箭头函数和对象分解

在主要组成部分:

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} />
    )
  }

}
class ReactMain extends React.Component {

  constructor(props) {
    super(props);
    // bind once here, better than multiple times in render
    this.handleChange = this.handleChange.bind(this);
    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} />
    )
  }

}
类ReactMain扩展React.Component{
建造师(道具){
超级(道具);
this.state={fruit:props.item.fruit};
}
handleChange=(事件)=>{
this.setState({[event.target.name]:event.target.value});
}
saveItem=()=>{
常量项={};
item.fruit=this.state.fruit;
//根据需要对项目对象执行更多操作(例如保存到数据库)
}
render(){
返回(
)
}
}
包含的组件(现在是无状态函数):

export const ReactExample=({name,value,handleChange})=>(
苹果
香蕉
蔓越莓
)
先前的答案(使用绑定):

在主要组成部分:

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} />
    )
  }

}
class ReactMain extends React.Component {

  constructor(props) {
    super(props);
    // bind once here, better than multiple times in render
    this.handleChange = this.handleChange.bind(this);
    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} />
    )
  }

}
类ReactMain扩展React.Component{
建造师(道具){
超级(道具);
//在此处绑定一次,比在渲染中多次绑定要好
this.handleChange=this.handleChange.bind(this);
this.state={fruit:props.item.fruit};
}
手变(活动){
this.setState({[event.target.name]:event.target.value});
}
saveItem(){
常量项={};
item.fruit=this.state.fruit;
//根据需要对项目对象执行更多操作(例如保存到数据库)
}
render(){
返回(
)
}
}
包含的组件(现在是无状态函数):

export const ReactExample=(道具)=>(
苹果
香蕉
蔓越莓
)
主组件维护水果(处于状态)的选定值,包括
class ReactMain extends React.Component {

  constructor(props) {
    super(props);
    // bind once here, better than multiple times in render
    this.handleChange = this.handleChange.bind(this);
    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} />
    )
  }

}
export const ReactExample = (props) => (
  <select name={props.name} value={props.value} onChange={props.handleChange}>
    <option value="A">Apple</option>
    <option value="B">Banana</option>
    <option value="C">Cranberry</option>
  </select>
)
<option disabled hidden value=''></option>
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>
    );
  }
} 
ComponentName.defaultProps = {
  propName: ''
}
<input
  type="select"
  defaultValue=""
  >
  <option value="" disabled className="text-hide">Please select</option>
  <option>value1</option>
  <option>value1</option>
</input>
.text-hide {
  font: 0/0 a;
  color: transparent;
  text-shadow: none;
  background-color: transparent;
  border: 0;
}
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>
  );
}
<Select defaultValue={[{ value: category.published, label: 'Publish' }]} options={statusOptions} onChange={handleStatusChange} />
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>
  )
}
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>
  )
}
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
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>
  )
}
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>
  )
}
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>
)
}