1
我有一個名爲Rooms
的根分支與firebase中的數組,以及名爲rooms
(數組)的應用中的狀態。當用戶輸入新房間名稱並按下提交時,我能夠使它成爲這樣,它被添加到Rooms
對象的末尾。如何從React中的數組狀態中刪除元素?
我想實現一個刪除方法,所以當旁邊的房間名稱x
按鈕用戶點擊,它就會從國家和火力刪除元素,但我沒有成功實現它。
我的起點是從SO similarly titled的線程。我無法執行工作的<li>
組件上的代碼。這是我有:
Chatroom.js
handleRemove(index) {
var array = this.state.rooms.slice();
array.splice(index, 1);
this.setState({
rooms: array
})
}
...
render(){
<div><DisplayChatrooms rooms={this.state.rooms} handleRemove={this.handleRemove.bind(this)} /></div>
DisplayChatrooms.js
class DisplayChatrooms extends React.Component{
render(){
console.log('handleRemove: ', this.props.handleRemove); //this prints out the handleRemove function just fine
var rooms = this.props.rooms.map(function(room, index){
return (
<li key={index}>{room} <a href="#">x</a></li>
)
})
return(
<div>
<ul>
{rooms}
</ul>
</div>
當我修改li
包括handleRemove
,它顯示了這個錯誤:Uncaught TypeError: Cannot read property 'props' of undefined
。
<li key={index}>{room} <a href="#" onClick={this.props.handleRemove}>x</a></li>
如何實現一種方法,允許用戶在點擊x時刪除該元素?