我尝试自动填充输入字段值。因此,我通过params将id
从Cards
组件发送到EditForm
组件,在EditForm
中,在其组件DidMount((中,我使用该id
,并通过id从数据库中获取post,从存储中获得post,并取出title
和description
。因此,我在表单中预先填充了从商店收到的值。现在,我被困在这里了。如何编辑此表单?使用我在输入字段的value
属性中设置的这些值,显然我无法键入任何内容,因为我想使其成为前缀填充。现在,我觉得我的方法是错误的。请帮忙。
Cards
import React, { Component } from "react"
class Cards extends Component {
handleEdit = _id => {
this.props.history.push(`/post/edit/${_id}`)
}
render() {
const { _id, title, description } = this.props.post
return (
<div className="card">
<div className="card-content">
<div className="media">
<div className="media-left">
<figure className="image is-48x48">
<img
src="https://bulma.io/images/placeholders/96x96.png"
alt="Placeholder image"
/>
</figure>
</div>
<div className="media-content" style={{ border: "1px grey" }}>
<p className="title is-5">{title}</p>
<p className="content">{description}</p>
<button onClick={() => {this.handleEdit(_id)}} className="button is-success">
Edit
</button>
</div>
</div>
</div>
</div>
)
}
}
export default Cards
EditForm
import React, { Component } from "react";
import { connect } from "react-redux";
import { getPost } from "../actions/userActions"
class EditForm extends Component {
componentDidMount() {
const id = this.props.match.params.id
this.props.dispatch(getPost(id))
}
handleChange = event => {
const { name, value } = event.target;
this.setState({
[name]: value
})
};
render() {
return (
<div>
<input
onChange={this.handleChange}
name="title"
value={this.props.post.post.title}
className="input"
placeholder="Title"
/>
<textarea
onChange={this.handleChange}
name="desctiption"
value={this.props.post.post.description}
className="textarea"
></textarea>
<button>Submit</button>
</div>
);
}
}
const mapStateToProps = store => {
return store;
};
export default connect(mapStateToProps)(EditForm)
定义2个状态标题和描述,并在提取它们后进行设置。然后通过onchange函数更新状态,并将状态作为值传递给输入和文本区域
import React, { Component } from "react";
import { connect } from "react-redux";
import { getPost } from "../actions/userActions"
class EditForm extends Component {
constructor() {
super();
this.state = {
title: '',
description: ''
};
componentDidMount() {
const id = this.props.match.params.id
this.props.dispatch(getPost(id))
}
componentWillReceiveProps(nextProps) {
if (nextProps.post !== this.props.post) {
this.setState({
title: nextProps.post.post.title,
description: nextProps.post.post.description,
});
}
}
handleChange = event => {
const { name, value } = event.target;
this.setState({
[name]: value
})
};
render() {
const { title, description } = this.state
return (
<div>
<input
onChange={this.handleChange}
name="title"
value={title}
className="input"
placeholder="Title"
/>
<textarea
onChange={this.handleChange}
name="description"
value={description}
className="textarea"
></textarea>
<button>Submit</button>
</div>
);
}
}
const mapStateToProps = store => {
return store;
};
export default connect(mapStateToProps)(EditForm)