【发布时间】:2017-03-07 02:14:39
【问题描述】:
我在 firebase 中有一个数组,其根分支名为 Rooms,应用程序中的状态名为 rooms(数组)。我能够做到,所以当用户输入新房间名称并按提交时,它被添加到 Rooms 对象的末尾。
我想实现一个删除方法,所以当用户点击房间名称旁边的 x 按钮时,它会从状态和 firebase 中删除该元素,但我没有成功实现它。
我的出发点是来自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 时删除该元素的方法?
【问题讨论】:
标签: javascript reactjs firebase firebase-realtime-database