我试图在table.the中以动态的方式设置每个字段的值,问题是当我更改一个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>
);
}
}
发布于 2018-10-15 02:57:32
您的示例缺少一些使其成为可运行应用程序的关键细节,因此这只是一种猜测,但我认为这取决于如何绑定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;
演示
https://stackoverflow.com/questions/52805751
复制相似问题