Q&A
Reactで入力されたタイトルとテキストを送信ボタンを押すと画面の下側に表示させる機能を実装していたのですが、
タイトルとテキストの入力を行い、送信ボタンを押すと配列の中の値が消えてしまい、画面に表示されません。
以下、問題のあるプログラムです
import './App.css';
import { useState } from 'react';
const getKey = () => Math.random().toString(32).substring(2);
function App2() {
const [items, setItems] = useState([]);
const handleAdd = (title,text) => {
setItems([...items, { key: getKey(),title, text}]);
};
return (
<div>
<meta charSet="UTF-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>メモ</title>
<div className="board-section">
<h2>メモアプリ</h2>
</div><Form onAdd={handleAdd}/>{console.log(items)} <List item={items} /> </div>
);
}
function Form({ onAdd }){
const [title,setTitle]=useState('');
const [text,setText]=useState('');
const handleChange =(e)=>setTitle(e.target.value);
const handleText = (e) =>setText(e.target.value);
const handleKeyDown = () =>{
onAdd(title,text);
setTitle('');
setText('');
};
return(
<>
<form className="form-section">
{console.log("タイトル"+title)}
<p>タイトル</p>
<input type="text" id="inputTitle" value={title} placeholder='タイトルを入力してください' onChange={handleChange}/>
<p>内容</p>
<textarea id="inputContent" value={text} placeholder="テキストを入力してください" rows={10} cols={30} onChange={handleText}/>
<br />
<button id="submitButton" type="submit" onClick={handleKeyDown}>送信</button>
</form>
</>
)};
function List({ item }){
return(
<>
<div className="thread-section">
<div className="single-thread">
<h3>{item.title}</h3>
<p>{item.text}</p>
</div>
</div>
</>
)};
export default App2;
質問の内容が分かりづらくてすみません、また、reactでのアプリ作成は初めてなのでプログラムが大きく間違っていたら大変申し訳ないです、、、
もし原因などお分かりでしたらご教授いただけますと幸いです。
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2022/06/24 05:35
2022/06/24 05:50