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标记文档.
小智 64
当你尝试设置以下内容的"selected"属性时,你可以做React警告你的事情<option>:
使用
defaultValue或value道具上<select>,而不是设置selected上<option>.
所以,你可以用options.value在defaultValue你的选择中
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首先,用基本的 React 功能组件回答最初提出的问题 - 两个带和不带 props 的示例,然后是如何在其他地方导入该组件。
\n接下来是相同的示例 - 但使用 Typescript 进行了增强。
\n然后是一个额外的结局 - 使用 Typescript 的语言选择器下拉组件。
\nFruitSelectDropdown,一个没有道具,一个有接受道具fruitDetectorimport 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}\nRun Code Online (Sandbox Code Playgroud)\n或者你可以让 FruitSelectDropdown 接受 props,也许你有一个输出字符串的函数,你可以使用fruitDetectorprops传递它
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}\nRun Code Online (Sandbox Code Playgroud)\n然后导入FruitSelectDropdown应用程序中的其他位置
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\nRun Code Online (Sandbox Code Playgroud)\nFruitSelectDropdown使用打字稿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}\nRun Code Online (Sandbox Code Playgroud)\n然后导入FruitSelectDropdown应用程序中的其他位置
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\nRun Code Online (Sandbox Code Playgroud)\nimport 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}\nRun Code Online (Sandbox Code Playgroud)\nCTS*_*_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)
这将成为默认值,当您选择一个有效选项时,您的状态将被设置
这是如何执行此操作的最新示例。从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)
使用 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)
| 归档时间: |
|
| 查看次数: |
319724 次 |
| 最近记录: |