我试图在表内以动态方式设置每个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>
);
}
}
答案 0 :(得分:0)
您的示例缺少使它可运行的应用程序的一些关键细节,因此,这只是猜测,但我认为这是您绑定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;