我有一个具有可控制输入的表格,该表格使用物料反应处于模态。我要做的就是使用可用数据填充表单,以便用户可以修改现有数据。我使用了其他stackoverflow线程中提到的解决方案,这些解决方案要求以这种格式使用TextField的Value属性Value = {this.state.name || ”,但对我不起作用。
class AddItemModal extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false,
name: '',
amount: 0,
date: moment().format('YYYY-MM-DD'),
single_transaction: {}
};
this.handleChange = this.handleChange.bind(this)
this.handleClose = this.handleClose.bind(this)
this.handleSaveChange = this.handleSaveChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleChange = name => event => {
this.setState({
[name]: event.target.value,
})
}
handleSaveChange() {
fetch('http://localhost:1337/users/update', {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'name=' + this.state.name + '&amount=' + this.state.amount + '&date=' + this.state.date,
})
.then((res) => {
this.setState({ recordAdded: true })
console.log("Res:", res, this.state.recordAdded);
fetch('http://localhost:1337/users', {
method: 'GET',
})
.then((response) => {
console.log(response)
return response.json()
})
.then((transactions) => {
this.props.dispatch({
type: 'SET_ENTRY',
transactions: transactions
})
this.setState({ recordAdded: false })
})
.catch(function (error) {
console.log('Request failed', error);
});
})
.catch(function (error) {
console.log('Request1 failed: ', error);
});
}
handleClose = () => {
this.props.dispatch({
type: 'GET_MODAL',
open: false,
single_transaction: {}
});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
let { open, single_transaction } = this.props.modal;
return (
<div>
<Dialog
open={open}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
onClose={this.handleClose}>
<DialogTitle id="alert-dialog-title">{"Add/Modify Transaction"}</DialogTitle>
<DialogContent>
<div>
<div>
<TextField
id="name"
label="Purpose"
type="text"
value={this.state.name}
onChange={this.handleChange('name')}
margin="normal"
autoFocus
/>
</div>
<div>
<TextField
id="amount"
label="Amount"
type="number"
value={this.state.amount}
onChange={this.handleChange('amount')}
margin="normal"
/>
</div>
<div>
<TextField
id="date"
label="Date"
type="date"
value={this.state.date}
onChange={this.handleChange('date')}
margin="normal"
/>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={this.handleSaveChange} variant="contained" color="primary">
Save Changes
</Button>
<Button onClick={this.handleClose} variant="contained" color="secondary">
Close
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}