0
我正在學習最近幾天的ReactJS,並且我遇到了通過循環呈現元素的特定問題。請扔在這個問題的一些光,當我們呼籲從PostList
塊removeItem
功能提供
在PostList功能塊通過循環呈現元素時在React中進行索引
這個腳本工作正常,我們有
<Post key = {index} ..... removeItem = {() => props.removeItem(index)}/>
和後功能塊我們有
<PostButton label = "x" handleClick = {props.removeItem}/>
但是如果我通過這個removeItem
功能的Post
塊,並呼籲像
功能在PostList功能塊,我們有
<Post key = {index} ..... removeItem = {props.removeItem}/>
和
在後功能塊,我們有
<PostButton label = "x" handleClick = {() => props.removeItem(props.key)}/>
Wrong Implemented Code 然後發生一些錯誤的REM val的項目,這是不正確的,其刪除按鈕被點擊的項目沒有被刪除,但是它的前者被刪除。我假定原因是從postList
變量中刪除元素會影響第二種情況下的索引,但在第一種情況下通過再次重新呈現postList
正確處理。 是否有人可以通過對索引,而處理元素,同時通過循環使它們是如何工作的一些對光反應消失
function PostButton(props){
var style = {
width:24,
height:24
}
return (
<button style = {style} onClick = {() => props.handleClick()}>{props.label}</button>
)
}
function PostText(props){
var style = {
border:"1px solid black",
width: props.width
}
return (
<div style = {style}>{props.text}</div>
)
}
function Post(props){
var style = {
display:"flex"
}
return (
<div style = {style}>
<PostButton label = "x" handleClick = {props.removeItem}/>
<PostText text = {props.title} width = "200"/>
<PostButton label = "+" handleClick = {props.incrementScore}/>
<PostText text = {props.score} width = "20"/>
<PostButton label = "-" handleClick = {props.decrementScore}/>
</div>
)
}
function PostList(props){
return (
<ol>
{
props.postList.map((item,index) =>
<Post key = {index}
title = {item.title}
score = {item.score}
incrementScore = {() => props.updateScore(index,1)}
decrementScore = {() => props.updateScore(index,-1)}
removeItem = {() => props.removeItem(index)}
/>
)
}
</ol>
)
}
class App extends React.Component{
constructor(props){
super(props)
this.state = {value:"", items : []}
}
handleChange(event){
this.setState({value:event.target.value})
}
addItem(){
var itemsCopy = this.state.items.slice()
var truncatedString = this.state.value.substring(0,20);
itemsCopy.push({"title":truncatedString,"score":0})
itemsCopy.sort((a,b)=>{
return b.score - a.score;
})
this.setState({items:itemsCopy,value:""})
}
removeItem(index){
var itemsCopy = this.state.items.slice()
itemsCopy.splice(index,1);
itemsCopy.sort((a,b) => {
return b.score - a.score
})
this.setState({items:itemsCopy})
}
updateScore(index,val){
var itemsCopy = this.state.items.slice()
itemsCopy[index].score += val
itemsCopy.sort((a,b) => {
return b.score - a.score
})
this.setState({items:itemsCopy})
}
render(){
return (
<div>
<input value = {this.state.value} onChange = {this.handleChange.bind(this)}/>
<button onClick = {() => this.addItem()}>Submit</button>
<PostList postList = {this.state.items}
updateScore = {this.updateScore.bind(this)}
removeItem = {this.removeItem.bind(this)}
/>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="root"></div>