TypeError:无法读取未定义的属性“name”-react
2020-09-17
894
我有一个带有“标题”和“内容”的表单。内容位于 ReactQuill 组件中,该组件可让您获得富文本。在添加该组件之前,我的“onChange”对于两个“输入”都运行良好。现在组件不同了,它不再起作用。
我收到以下错误:
这是 AddArticle.js 中的代码,表单就在这里:
import React, { Component } from "react";
import firebase from "../Firebase";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import renderHTML from "react-render-html";
class AddArticle extends Component {
constructor() {
super();
this.ref = firebase.firestore().collection("articles");
this.state = {
title: "",
content: "",
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
onSubmit = (e) => {
e.preventDefault();
const { title, content } = this.state;
this.ref
.add({
title,
content,
})
.then((docRef) => {
this.setState({
title: "",
content: "",
});
this.props.history.push("/");
})
.catch((error) => {
console.error("Error adding document: ", error);
});
};
render() {
return (
<div className="container">
<br></br>
<br></br>
<br></br>
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title text-center">Create a new article</h3>
</div>
<br></br>
<br></br>
<div className="panel-body">
<form onSubmit={this.onSubmit}>
<div className="form-group input-group-lg">
<label for="title">Title:</label>
<input
type="text"
className="form-control"
name="title"
value={this.state.title}
onChange={this.onChange}
placeholder="Title"
/>
</div>
<div className="form-group">
<label for="content">Content:</label>
<ReactQuill
theme="snow"
name="content"
value={this.state.content}
onChange={this.onChange}
placeholder="Content"
/>
</div>
<button type="submit" className="btn btn-success">
Submit
</button>
</form>
</div>
</div>
</div>
);
}
}
export default AddArticle;
1个回答
标题输入的 onChange 接收包含名称和值的事件。
另一方面,Quill 组件的 onChange 接收实际内容。
总之,您应该使用:
onTitleChange = (e) => {
this.setState({ title: e.target.value });
};
onContentChange = (content) => {
this.setState({ content: content });
};
并将这些处理程序适当地传递给您的标题输入和 quill 组件。
Louis Coulet
2020-09-17