【发布时间】:2019-01-25 12:54:36
【问题描述】:
这里是初级程序员。
我一直在尝试使用 CSS 定位来修复此代码中的 Input 元素。基本上我想做的是让聊天输入在我滚动的任何地方浮动,我认为这将是使用 CSS 固定定位的简单修复。
但是,当我尝试使用许多不同的 CSS 方法来定位 Input 元素时,我陷入了僵局。每次我“修复”位置时,它都会破坏页面其余部分的布局。如果代码未完善,我深表歉意,因为它是一个协作项目。我想要的只是让输入保持固定,无论我在哪里滚动,尽管我不确定问题是否在代码中更深层次。
我怀疑这可能与下面的 JSX (Javascript) 文件中“输入”的呈现方式有关。但在我完全确定我可以修复它之前,我不想弄乱另一个开发人员的代码。如果之前有人问过这个问题,我深表歉意;我漫游了数周寻找解决方案,但找不到。如果我遗漏任何细节,我将非常乐意提供。
编辑:我正在进行的项目是开源的。您可以找到项目here。
我正在处理的 git 分支当前是“个人资料页面”,其中包含以下文件:
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>
【问题讨论】:
-
您能否提供这个问题的可行示例?
-
我很抱歉;我应该知道该怎么做,但是我刚开始的时候不知道怎么做。我可以提供 github 项目并参考启动服务器的说明,尽管每次尝试编辑上述代码 sn-p 时都会收到 syntaxError。 The current branch for this code is "profile-page."
标签: javascript html css reactjs positioning