我似乎无法弄清楚为什么我的表单会在提交时清除prev数据。我有一个编辑按钮,当点击时弹出一个窗体。如果我编辑名称字段但不编辑生日日期字段,则名称将更改,生日日期将消失。这可能是一个简单的愚蠢错误,但第二组眼睛可能有帮助
class Card extends Component {
constructor(props) {
super(props);
this.state = {
dataEditingMode: false,
planetSelection: this.props.homeWorld,
}
}
onEditDeets() {
this.setState({
dataEditingMode: !this.state.dataEditingMode
});
}
onSaveDeets(element) {
element.preventDefault();
this.props.onSavingEditedDeets(
this.props.id,
this.refs.personName.value,
this.refs.personBirthday.value,
this.refs.personHomeWorld.value)
this.setState({
dataEditingMode: false
});
}
onEditPlanetSelection(event) {
this.setState({
planetSelection:event.target.value
});
}
render() {
let getHomeWorld = (planetID) => {
for (var i = 0; i < this.props.planetList.length; i++) {
if (this.props.planetList[i].id === planetID) {
return this.props.planetList[i].name;
}
}
return 'planet does not exist.'
}
let name = this.props.name;
let imageURL = this.props.imageURL;
let birthday = this.props.birthday;
let homeWorld = this.props.homeWorld;
let dataEditingForm;
if (this.state.dataEditingMode === true) {
dataEditingForm = <form
onSubmit={this.onSaveDeets.bind(this)}>
<span>Name: </span>
<input type="text" ref="personName" />
<span>Birthday: </span>
<input type="text" ref="personBirthday" />
<span>Homeworld: </span>
<select
value={this.state.planetSelection}
ref="personHomeWorld"
onChange={this.onEditPlanetSelection.bind(this)}
>
{this.props.planetList.map((planet)=>{
return <option
key={planet.id}
value={planet.id}
>
{planet.name}
</option>
})}
</select>
<button>Save Deets</button>
</form>
} else {
dataEditingForm = <div></div>
}
return (
<div className='card'>
<div className='card-content'>
<div className='card-name'>{name}</div>
<img src={imageURL} alt='profile'/>
<p>
<span>Birthday:</span>
<span>{birthday}</span>
</p>
<p>
<span>Homeworld:</span>
<span>{getHomeWorld(homeWorld)}</span>
</p>
<p>
<span>
<button type="button" onClick={this.onEditDeets.bind(this)}>Edit Card Deets</button>
</span>
</p>
{dataEditingForm}
</div>
</div>
);
}
}
export default Card;
答案 0 :(得分:1)
基本上,您是根据表单的值更新您的状态,无论它们是否被更改。
要进行简单的更改,您只需将input
代码的默认值设置为州
<span>Name: </span>
<input type="text" ref="personName" defaultValue="{name}" />
<span>Birthday: </span>
<input type="text" ref="personBirthday" defaultValue="{birthday}"/>
此外,在这种情况下,我更喜欢基于表单状态执行这样的编辑,但是根据您想要处理onChange的场景。
例如,在设置页面中,您可能希望某些切换立即生效。然后你应该处理onChange并直接更新状态。