简体   繁体   English

反应组件渲染不正确

[英]React components rendering incorrectly

I have a react project, a recipe box, which includes the ability to open a recipe and add/delete ingredients. 我有一个React项目,一个食谱框,其中包括打开食谱和添加/删除配料的功能。 Here is a fiddle . 这是一个小提琴 You can click the recipe name to open the recipe. 您可以单击配方名称以打开配方。 There is an edit button which reveals the delete button and gives the option to change the name of the ingredients. 有一个编辑按钮,显示删除按钮,并提供更改成分名称的选项。 When the 'delete ingredient' button is pressed, the last ingredient appears to always be deleted, regardless of which ingredient is selected, but when the 'done' button is clicked and the editable input boxes change back to text, the correct change is shown, the proper ingredient deleted and the last ingredient remains. 当按下“删除成分”按钮时,无论选择哪种成分,最后一个成分似乎总是被删除,但是当单击“完成”按钮并且可编辑的输入框变回文本时,将显示正确的更改,正确的成分被删除,最后的成分保留。 Though this works functionally, it's obviously not very UI friendly, and I wondered why this was happening. 尽管此功能可以正常工作,但它显然不是非常友好的UI,我想知道为什么会这样。 Any help would be great. 任何帮助都会很棒。

jsFiddle jsFiddle

class Input extends React.Component {
  render() {
   const array = this.props.update;
   let booleanButton = null;
   if (this.props.ingr) {
////////////////////////////
// here is the button's JSX
    booleanButton = <button onClick=
    {this.props.handleDeleteIngredient.bind(this, array)}>delete 
    ingredient</button>;
///////////////////////////
   }
 return (<div><form><input type="text" defaultValue={this.props.text} 
   onChange={this.props.onChange.bind(this, array)} /></form>{booleanButton}
  </div>)
  }
}

And the handler: 和处理程序:

handleDeleteIngredient(data, e ) {
  var key = data[2];
  var ingrs = this.state.ingrs;
  ingrs.splice(key, 1);
  this.setState({ingrs:ingrs});
}

Your description is quiet confusing, and according the your fiddle code I think your problem is caused by not setting a good key for your list Item. 您的描述令人困惑,根据您的小提琴代码,我认为您的问题是由于未为列表项设置好的键而引起的。
from what it looks in this line, you don't have a key={ingrs[i]} props, try set it to id see it will work, but making ingrediant name as key is probably not a good idea, try to give an actual id. 从这一行的外观来看,您没有key = {ingrs [i]}道具,尝试将其设置为id即可使用,但是将唯一名称作为关键字可能不是一个好主意,请尝试给出实际编号。

 ingrList.push(<Input key={ingrs[i]} handleDeleteIngredient={this.handleDeleteIngredient.bind(this)} id={id} update={[this.props.objectIndex, "ingrs", i]} onChange={this.onInputChangeIng.bind(this)} text={ingrs[i]} />); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM