reactjs - React - 处理多个 SelectField
问题描述
我正在尝试在表中以动态方式设置每个 selectField 的值。问题是当我更改一个 selectField 时,它没有更新我的 selectfield setState,也没有更新 selectfield 中的 selectfield 值。我不知道我是如何可以在我的下拉列表中更改选定的字段值
class Forms extends React.Component {
constructor(props) {
super(props);
this.state = {
month: [],
};
}
handleMonth(index, value){
let tmp = [...this.state.month];
tmp[index] = value;
this.setState({ month: tmp});
}
render() {
return (
<Table>
<TableHead>
<TableRow>
<TableCell style={{ color: "rgb(131, 132, 133)" }}>
Profiles:
</TableCell>
<TableCell style={{ color: "rgb(131, 132, 133)" }}>
Value
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{Profiles.map((row,index) => {
return (
<TableRow key={row.id}>
<TableCell
component="th"
style={{ color: "rgb(131, 132, 133)" }}
scope="row"
>
{row.id}
</TableCell>
<TableCell>
<Select
value={this.state.month[index] || null}
onChange={this.handleMonth.bind(this, index)}
style={{ position: "relative", width: "10vw" }}
>
{
this.props.data!==undefined ?
this.props.daployment.map(item => {
return <MenuItem value={item.name}>{item.name}</MenuItem>
}):""
}
</Select>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
);
}
}
解决方案
您的示例缺少一些使其成为可运行应用程序的关键细节,因此这只是推测,但我认为这与您绑定 onChange 方法的方式有关。这是我的一个 React 应用程序中的一个精简示例。
请注意,onChange 函数将接收一个事件作为第一个参数,并且我没有从我的render
方法内部绑定它。
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
regions: [
{ name: 'Select Region', value: null },
{ name: 'East', value: 'east' },
{ name: 'West', value: 'west' },
{ name: 'Pacific', value: 'pacific' },
{ name: 'Atlantic', value: 'atlantic' }
],
names: [
{ name: 'Select Name', value: null },
{ name: 'Peter', value: 'peter' },
{ name: 'Paul', value: 'paul' },
{ name: 'Mary', value: 'mary' }
],
region: '',
name: ''
};
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
const { regions, names, region, name } = this.state;
return (
<div>
<select
onChange={this.handleChange}
value={region}
name="region"
>
{regions.map(item => (
<option
key={item.value}
value={item.value}
>
{item.name}
</option>
))}
</select>
<select
onChange={this.handleChange}
value={name}
name="name"
>
{names.map(item => (
<option
key={item.value}
value={item.value}
>
{item.name}
</option>
))}
</select>
<p>Selected Region: {region}</p>
<p>Selected Name: {name}</p>
</div>
);
}
}
export default App;
演示
推荐阅读
- python - 从 Python 2 迁移到 3 时出现 Tensorflow 输入馈送错误
- python - 如果 Selenium 中不存在元素,如何跳过
- swift - 如何每月最多显示一次 iOS 的区域通知?
- excel - 用于多个标签的 Excel 数据透视表
- javascript - 我可以在 Bulma 中使用新的 CSS 自定义属性(变量)吗?
- c++ - 如何在 Ubuntu 上提高我的程序磁盘读取速度?
- http - HTTP 响应是否指示接收者的地址或类似的地址?
- php - 在 PHP 中将字符串编码为文件路径片段
- javascript - 使用箭头键递增
- javascript - 主页组件仅在刷新时加载(而不是在初始加载时),竞争条件?