我想从数组中删除一个元素,但我没有得到,我的代码是:
Author must be exist
代码是什么? 他渲染一个数组的元素,3中有3个。数组中的每个元素都有一个“删除”按钮,每次点击它时,一个元素都会从屏幕上移出。
代码和按钮是:const renderCount = state => {
const peopleHtml = state.filteredPeople.map(person => {
const personHtml = document.createElement('LI');
const personName = document.createTextNode(person.name);
const buttonDelete = document.createElement('Button');
const textOfButtonDelete = document.createTextNode('Delete');
buttonDelete.appendChild(textOfButtonDelete);
personHtml.appendChild(personName);
personHtml.appendChild(buttonDelete);
buttonDelete.onclick = function() {
return {...state,filteredPeople : state.filteredPeople.filter( (item, index) => index !=="Jean")}
}
return personHtml;
});
resultado.innerHTML = '';
peopleHtml.forEach(personHtml => resultado.appendChild(personHtml));
};
export default renderCount;
。
谢谢,下午好。
答案 0 :(得分:0)
这不是在reactjs中正确的方法。 React相信Virtual DOM。您的状态值和HTML元素将相互通信,您不需要使用appendChild或removeChild来更新它们,只需更新状态值即可。有些事情如下
render()
{
return (
<div>
<ul>
{this.state.filteredPeople.map(person => { =>
<li>
{person.name}
<button onClick={this.deleteme.bind(this,person.id)}>Delete</button>
</li>
)}
</ul>
</div>
);
}
deleteme(index){
let initial_val = this.state.contents.slice();
let obj_to_del= initial_val.find(person => person.id === id);
initial_val.remove(obj_to_del);
this.setState({people:initial_val});
}