使用表格向React.js应用程序中的Firebase数据库添加记录时出现问题

时间:2018-09-08 06:51:06

标签: javascript reactjs firebase firebase-realtime-database

我正在使用一个React.js应用程序。我在Firebase中拥有聊天室的数据库,并且需要放置带有提交按钮的文本字段表单才能添加聊天室。到目前为止,这是我的RoomList组件中的代码:

import React, { Component } from 'react';

class RoomList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            rooms: [],
            newRoomName: 'New room',
        };
        this.roomsRef = this.props.firebase.database().ref('rooms');
    };

    componentDidMount() {
        this.roomsRef.on('child_added', snapshot => {
            const room = snapshot.val();
            room.key = snapshot.key;
            this.setState({ rooms: this.state.rooms.concat( room ) })
        });
    }

    createRoom = (e) => {
        const newRoomName = this.state.rooms.name();
        this.roomsRef.push({
            name: this.state.newRoomName
        });
    }

    render() {
        return (
            <div>
                <div>
                    {this.state.rooms.map ( (rooms) =>
                        <section className="RoomList" key={rooms.key}>
                        {rooms.name}
                        </section>
                    )}
                </div>
                <form onSubmit={this.createRoom.bind(this)}>
                    <input placeholder='New room' 
                        value={this.state.newRoomName}
                        onChange={e => this.setState({newRoomName: e.target.value})}
                    />
                    <input type='submit' value='Create room' />
                </form>
            </div>  
        )}

    }

export default RoomList;

0 个答案:

没有答案