为什么我不能使用CSS在此特定Input元素上使用固定定位?

时间:2018-08-18 22:35:42

标签: javascript html css reactjs positioning

这里是初学者。
我一直在尝试使用CSS定位来修复此代码中的Input元素。本质上,我想做的是让chat Input浮动到我滚动的任何地方,我认为使用CSS固定定位可以轻松解决此问题。

但是,由于尝试使用许多不同的CSS方法来放置Input元素,我陷入了僵局。每次我“固定”位置时,它都会破坏页面其余部分的布局。对于该代码是一个协作项目,如果不完善,我深表歉意。我只想让输入保持固定,而不管我在哪里滚动,尽管我不确定问题是否在代码中更深层。

我怀疑这可能与下面的JSX(Javascript)文件中呈现“输入”的方式有关。但是我绝对不会打扰其他开发人员的代码,直到我绝对肯定可以修复它为止。抱歉,是否曾有人问过?我漫游了数周以寻找解决方案,但找不到解决方案。如果我缺少任何详细信息,我将非常乐意提供。

编辑:我正在处理的项目是开源的。您可以找到项目here。 我正在使用的git分支当前是'profile-page',具有以下文件: sensorium-web \ src \ components \ user \ profileComponents \ styles \ profile.css
sensorium-web \ src \ components \ user \ Profile.jsx

您可以在终端中使用“ npm start”打开测试服务器。虽然您必须先注册才能访问聊天室。

import React, { Component, ReactDOM } from 'react'
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { Image } from 'react-bootstrap';
import {Container, Row, Col, Jumbotron} from 'reactstrap';
import Fade from 'react-reveal/Fade';
import '../style/Home.css';
import '../style/style.css';
import '../style/responsive.css';
import './profileComponents/styles/profile.css';
import firebaseConf, {firebase} from './../../config/FirebaseConfig';
import ProfileDetails from './profileComponents/ProfileDetails';
import ProfileMenu from './profileComponents/ProfileMenu';
import Chat from './profileComponents/Chat';
import { Input, Button } from 'react-chat-elements';

import moment from 'moment';

class Profile extends Component {

    constructor(props, context) {
        super(props,context);
        console.log(props);
        this.state = {
            authUser: props.authUser,
            dateOfBirth: '',
            desiredClusters: {},
            name: '',
            lastName:'',
            secondLastName: '',
            numSensatesInCluster: 0,
            sensatesInCluster: [],
            photo: require('./profilepic.png'),
            messages: []
        };

        this.db = firebaseConf.firestore();
        const settings = { timestampsInSnapshots: true};
        this.db.settings(settings);

        this.clusterChatId = '';
        this.sensateListener;
        this.clusterListener; 
        this.chatListener;

        this.sensatesQueryArray = [];
        this.sensatesList = [];

        this.sensateListener = this.db.collection("sensies").doc(this.state.authUser.uid)
        .onSnapshot((doc) =>{
            if(doc.exists){
                const sensate = doc.data();
                
                this.clusterListener = this.db.collection("clusters").where("sensates."+doc.id, "==", true)
                .onSnapshot((querySnapshot) =>{
                    querySnapshot.forEach((doc)=>{
                        const clusterData = doc.data();

                        let numSensatesInCluster = 0;
                        this.sensatesQueryArray = [];
                        
                        Object.keys(clusterData.sensates).forEach((sensateId)=>{
                            if(clusterData.sensates[sensateId]){
                                numSensatesInCluster = numSensatesInCluster + 1;
                                this.sensatesQueryArray.push(
                                    this.db.collection("sensies").doc(sensateId).get()
                                );
                            }
                        });
                        //subtract his own reference
                        numSensatesInCluster = numSensatesInCluster - 1;
                        this.setState({numSensatesInCluster: numSensatesInCluster});

                        this.sensatesList = [];

                        Promise.all(this.sensatesQueryArray).then((sensatesMembers)=>{
                            sensatesMembers.forEach((sensateMemberData)=>{
                                if(sensateMemberData.exists){
                                    const sensateMemberInfo = sensateMemberData.data();
                                    this.sensatesList.push({
                                        uid: sensateMemberInfo.uid,
                                        name: sensateMemberInfo.name,
                                        lastName: sensateMemberInfo.lastName
                                    });
                                }
                            });
                            this.setState({
                                sensatesInCluster: this.sensatesList
                            });
                        }).catch((err)=>{
                            console.log(err);
                        });

                        //Cluster chat
                        this.clusterChatId = doc.id;
                        this.chatListener = this.db.collection("clusters").doc(this.clusterChatId).collection('messages')
                        .orderBy("date", "desc").limit(50)
                        .onSnapshot((messages)=>{
                            var chatMessages = [];

                            messages.forEach((message)=> {
                                var msg = message.data();

                                //position
                                if(msg.user._id === this.state.authUser.uid){
                                    msg['position'] = 'right';
                                }else{
                                    msg['position'] = 'left';
                                }
                                console.log()
                                if(msg.date && msg.date.seconds){
                                    msg['dateString'] = moment(msg.date.seconds * 1000).format('hh:mm a');
                                    msg['date'] = moment(msg.date.seconds * 1000);
                                }
                                msg['title'] = msg.user.name;
                                msg['titleColor'] = 'blue'

                                chatMessages.push(msg);
                                
                            });

                            var count = 0;
                            var chatMessagesReversed = [];
                            for(var i=chatMessages.length-1; i>=0; i--){
                                count = count + 1;
                                chatMessagesReversed.push(chatMessages[i])
                            }
                            
                            this.setState({
                                messages: chatMessagesReversed
                            })
                              
                        });

                    });
                });

                this.setState(sensate);
                
            }else{
                console.log("Sensate doesn't exist");
                alert("Sensate doesn't exist");
            }
        });
        
    }

    sendMessageToChat(){
        const serverDate = firebase.firestore.FieldValue.serverTimestamp();
        console.log(serverDate);
        const date = new Date();
        const dateNumber = date.getTime();
        const message = {
            "_id": dateNumber,
            "text": this.chatText.state.value,
            "createdAt": serverDate,
            "system": false,
            "user": {
              "_id": this.state.authUser.uid,
              "name": this.state.name,
              "avatar": this.state.photo
            },
            "id": dateNumber,
            "type": "text",
            "date": serverDate,
            "status": "sent",
            "avatar": this.state.photo
        }
        console.log(message, this.chatText.state.value)
        this.chatText.clear();
        this.db.collection("clusters").doc(this.clusterChatId).collection('messages').add(message).then((res)=>{
            console.log(res, 'update state');
        }).catch((err)=>{
            console.log(err);
        });
    }

    componentDidUpdate(prevProps) {
        if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) {
          window.scrollTo(0, 0)
        }
    }

    logout(){
        //unsubscribe from all listeners to avoid memory leaks
        this.sensateListener();
        this.clusterListener();
        if(this.chatListener){
            this.chatListener();
        }

        firebaseConf.auth().signOut().then(()=> {
            
            this.props.history.push("/");

        }).catch((error)=> {
            console.log(error);
            alert('An error occurred during sign-out.');
            this.props.history.push("/");
        });
    }
    
    render() {

        return (
            <Row noGutters id="outer-container">

                <Col md={3} className="no-padd">
                    <ProfileMenu photo={this.state.photo} name={this.state.name} 
                        lastName={this.state.lastName} numSensatesInCluster={this.state.numSensatesInCluster}
                        sensatesInClusterData={this.state.sensatesInCluster}
                        menuOpen={this.props.menuOpen} handleStateChange={this.props.handleStateChange} 
                        bigScreen={this.props.bigScreen}>
                    </ProfileMenu>
                    <p>{this.props.menuOpen}</p>
                </Col>
                
                <Col md={9} className="mt-7" id="page-wrap">

                        <Chat messages={this.state.messages}/>

                    <div className='input'>
                    <Input
                            placeholder="Type your message"
                            defaultValue=""
                            
                            ref={(input) => { this.chatText = input; }} 
                            multiline={true}
                            // buttonsFloat='left'
                            onKeyPress={(e) => {
                                if (e.shiftKey && e.charCode === 13) {
                                    return true;
                                }
                                if (e.charCode === 13) {
                                    if(this.chatText.state.value && /\S/.test(this.chatText.state.value)){
                                        this.sendMessageToChat();
                                    }
                                    
                                    e.preventDefault();
                                    return false;
                                }
                            }}
                            rightButtons={
                                <Button
                                    text='Send'
                                    type='outline'
                                    color='black'
                                    onClick={this.sendMessageToChat.bind(this)} />
                            } />
                    </div>
                </Col>
            </Row>
        )
    }
}

export default withRouter(Profile);
.no-padd{
    padding: 0 !important;
}

.input{
    flex: 1 0 auto;
    bottom: 0px;
    min-width: 50%;
}

.mt-7 {
    position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
    <meta name="theme-color" content="#000000">

    <meta name="keywords" content="Sense8 Sensorium sensorium.online sensates find cluster">
    <meta name="description" content="Sensorium.Online is a social networking website based on the idea of Sensorium from Netflix original series Sense8.">
    <meta property="og:title" content="Sensorium.online | Pre-registration">
    <meta property="og:description" content="Sensorium.Online is a social networking website based on the idea of Sensorium from Netflix original series Sense8.">
    <meta property="og:image" content="%PUBLIC_URL%/assets/sense.jpg">
    <meta property="og:url" content="sensorium.online">
    <meta name="twitter:site" content="@SensoriumApp" />
    <meta name="twitter:card" value="Sensorium.Online is a social networking website based on the idea of Sensorium from Netflix original series Sense8." />
    <meta name="twitter:image" content="%PUBLIC_URL%/assets/sense.jpg" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/index.css">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="%PUBLIC_URL%/assets/stylesheets/bootstrap337.min.css" >
    <!-- <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> -->
    <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
    <!-- MDB theme -->
    <link href="%PUBLIC_URL%/assets/stylesheets/mdb.min.css" rel="stylesheet">


    <title>Sensorium</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    
    
    <!-- JQuery -->
    <script type="text/javascript" src="%PUBLIC_URL%/assets/javascript/jquery321.min.js"></script>
    <!-- MDB core JavaScript -->
    <script type="text/javascript" src="%PUBLIC_URL%/assets/javascript/mdb.min.js"></script>
    <!-- Socials share -->
    <script async src="%PUBLIC_URL%/assets/javascript/addtoany.js"></script>
    
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您应该尝试将输入元素包装在div元素中,以进行固定定位。