【发布时间】:2019-10-06 20:03:53
【问题描述】:
我是 Reactjs 的新手。我正在尝试创建一个页面,用户可以在其中编辑自己的帖子。因此,文本输入的值是用户在发布帖子时输入的值。现在,当我尝试更改文本输入中的现有文本时,表单中可用的值会被清除,用户必须重新输入数据。
我需要用户更改输入文本中的现有文本,而不是重新输入。这是我的代码。
import React, { Component } from 'react'
class EditProduct extends Component {
constructor(props) {
super(props)
this.state = {
product: []
}
this.handleChange = this.handleChange.bind(this)
}
componentDidMount() {
fetch("http://localhost:8000/lender/edit_product_display.php?id=" + this.props.match.params.productId)
.then(response => response.json())
.then((productResponse) => {
this.setState({
product: productResponse
})
})
.catch(error => console.log(error))
}
handleChange(event){
const name = event.target.name
this.setState({
product: [{
[name]: event.target.value
}]
})
}
render() {
return(
<div key={this.state.product.product_id}>
Product ID: {this.props.match.params.productId}
<br /><br />
Product Name:
<input
type="text"
name="product_name"
value={this.state.product.product_name}
onChange= {this.handleChange}
/>
<br />
Product Model:
<input
type="text"
name="product_model"
value={this.state.product.product_model}
onChange={this.handleChange}
/>
</div>
)
}
}
export default EditProduct
【问题讨论】:
-
您的值
value={this.state.product.product_name}与您用于状态的结构不匹配,即产品设置为数组product: []您的值需要反映这一点,例如this.state.product[0].product_name或更改您的状态结构
标签: javascript reactjs