[英]Data from database displaying in the State but not on screen in React.js
[英]State is getting input from user but not displaying on webpage in React.js
實際上,我正在 React.js 中構建 Facebook Mesenger Clone,並使用了 Material UI。 當我們運行代碼時,它會要求輸入用戶名。 提供后,我們可以在應用程序中發送消息。 但是一旦我們發送消息,我們只會在屏幕上打印用戶名 . 該消息未顯示在網頁上。 這是 App.js 代碼:
import React, {useEffect, useState} from 'react';
import {Button, FormControl, Input, InputLabel} from "@material-ui/core";
import Message from "./Message";
import './App.css';
function App() {
const [input, setInput] = useState('');
const [messages, setMessages] = useState([]);
const [username, setUsername] = useState('');
useEffect(() => {
setUsername(prompt('Please enter your name'));
}, [])
const sendMessage = (event) => {
event.preventDefault();
setMessages([...messages, {username: username, text: input}]);
setInput('');
}
return <div className="App">
<h1>Hey Mate! 😃</h1>
<h2>Welcome {username}</h2>
<form>
<FormControl>
<InputLabel>Enter a message...</InputLabel>
<Input value={input} onChange={event => setInput(event.target.value)}/>
<Button disabled={!input} variant="contained" color="primary" type='submit' onClick={sendMessage}>Send
Message</Button>
</FormControl>
</form>
{
messages.map(message => <Message username={username} message={message}/>)
}
</div>
}
export default App;
這是消息組件的代碼:
import React from "react";
import {Card, CardContent, Typography} from "@material-ui/core";
import './Mesage.css';
function Message(message, username) {
const isUser = username === message.username;
return (
<div className={`message ${isUser && 'message_user'}`}>
<Card className={isUser ? "message_userCard" : "message_guestCard"}>
<CardContent>
<Typography color="white" variant="h5" component="h2">
{message.username}: {message.text}
</Typography>
</CardContent>
</Card>
</div>
)
}
export default Message;
請幫助我
您在Message
組件中獲取道具錯誤。 只需將其更改為
function Message({ message, username }) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.