React 应用程序中的 onChange 未触发
2018-07-22
5468
当我的组件中表单内的字段发生更改时,我很难触发 onChange 事件。当我在表单中进行更改时,编辑是允许的,但我在浏览器控制台中收到以下错误
bundle.js:57140 Uncaught TypeError: 无法设置 null 的属性 ''
关于如何解决此问题的任何想法都将非常有帮助!
import React from 'react';
import ReactDOM from 'react-dom';
import autoBind from 'react-autobind';
import Form from 'grommet/components/Form';
import TextInput from 'grommet/components/TextInput';
import NumberInput from 'grommet/components/NumberInput';
import DateTime from 'grommet/components/DateTime';
import FormFields from 'grommet/components/FormField';
export default class OverviewEditPane extends React.Component {
constructor(props) {
super(props);
autoBind(this);
this.onOverviewChange = this.onOverviewChange.bind(this)
}
onOverviewChange(event) {
let state = this.state;
let field = event.target.name;
let value = event.target.value;
console.log(field);
state[field] = value;
this.setState({state});
}
render () {
return (
<table>
<FormFields>
<tbody>
<tr>
<td>{this.props.overview.map((P) => {return <TextInput size='small' key={P.id} id={P.id} value={P.FName} onChange={this.onOverviewChange} />;})}</td>
</tr>...
2个回答
{ state } 是
{ state: state } 的简写。您真正想要做的是仅更新状态中的一个字段,而不是将整个当前状态设置为
state
键。
另外,请确保不要直接改变
state
对象。
onOverviewChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
}
Tholle
2018-07-22
您在此处尝试实现的操作是错误的,但您需要(想要)执行的操作可能是这样的:
//Here's your updated function:
onOverviewChange(e) {
const { name, value } = e.target; // Dectructuring name and value event
this.setState({ [name]: value }); // Setting the state to it's new key/ value pairs
}
.... 稍后在您的代码中,您将使用此函数触发
onChange
方法,如下所示:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.onOverviewChange = this.onOverviewChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
onOverviewChange(e) {
const { name, value } = e.target; // Dectructuring name and value event
this.setState({ [name]: value }); // Setting the state to it's new key/ value pairs
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text"
// Here we associate it with our state
name="value"
// Here's where we make use of our function
onChange={this.onOverviewChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(<Example/>, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
Dženis H.
2018-07-23