我正在创建所谓的食谱盒,您应该可以在其中制作add/edit/delete
食谱。初始渲染部分似乎工作正常,但是当涉及到状态和更新 html 时,我正在挣扎,具体取决于更改的内容:现有配方是否被修改、删除或添加了新配方。
目前我在编辑配方时实现了状态更改触发器。通过阅读各种文章,我得出的结论是,如果您想在与其他元素交互时从另一个元素读取值(在我的情况下,input
当button
元素被点击时从元素中读取),我需要添加状态以在输入时直接跟踪输入和然后使用该状态来触发我想要的(在我的情况下,我只使用所谓的挂起状态中的值并在按下该按钮时设置为正常状态)。
但它似乎不起作用。虽然我可能做错了什么。
这是我实现状态的部分:
class RecipeComponent extends React.Component {
constructor(props){
super(props);
this.state = {
title: '',
pendingTitle: '',
ingredients: '',
pendingIngredients: '',
}
}
handleChange(e, key){
let obj = {};
obj[key] = e.target.value;
this.setState(obj);
}
handleClick(){
this.setState(
{title: this.pendingTitle, ingredients: this.pendingIngredients});
}
_renderModal(target, ctx){
return (
<div className="modal fade" id={target} role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">×</button>
<h4 className="modal-title">{ctx.title}</h4>
</div>
<div className="modal-body">
<div className="form-group">
<label htmlFor="title" className="control-label"><span>Recipe</span></label>
<input type="text" id="title" className="form-control" placeholder="Recipe Name" defaultValue={ctx.recipeTitle ? ctx.recipeTitle : ''}
onKeyUp={(e) => this.handleChange(e, 'pendingTitle')}
/>
</div>
<div className="form-group">
<label htmlFor="ingredients" className="control-label"><span>Ingredients</span></label>
<input type="text" id="ingredients" className="form-control" placeholder="Enter Ingredients, separated by commas" defaultValue={ctx.ingredients ? ctx.ingredients : ''}
onChange={(e) => this.handleChange(e, 'pendingIngredients')}
/>
</div>
</div>
<div className="modal-footer">
{/*Seems to not update state properly*/}
<button type="button" className="btn btn-primary" onClick={() => this.handleClick()} data-dismiss="modal">{ctx.title}</button>
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
);
}
...
...
{/*Here title from state is never set*/}
// Should this.state.title replace default title?
recipeTitle: this.state.title || recipe.title,
}
完整代码可以在这里找到(如果很难理解我的意思,你也可以测试它当前的工作方式。尝试打开任何配方,编辑它并按下按钮Edit Recipe
,什么都不会发生,配方标题不会改变):https://codepen.io/andriusl/pen/LjxYQo
您直接访问this.pendingTitle
而不是this.state.pendingTitle
. 所以把它改成
handleClick(){
this.setState(
{title: this.state.pendingTitle, ingredients: this.state.pendingIngredients});
}
并将此代码更改为
<a data-toggle="collapse" data-target={anchor_target}
href={anchor_target} className="collapsed">{this.state.title||recipe.title}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句