当我更改组件中表单中的字段时,很难触发onChange事件。当我在表单中进行更改时,允许编辑,但在浏览器控制台中出现以下错误
bundle.js:57140未捕获的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>...
答案 0 :(得分:3)
{ state }
是{ state: state }
的简写。您真正想做的是只更新状态中的一个字段,而不是将整个当前状态设置为state
键。
还要确保您不直接对state
对象进行变异。
onOverviewChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
}
答案 1 :(得分:0)
您要在此处实现的目标是错误的,但您可能需要做的是:
//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>