前提
React.jsを用いて簡単なTodoリストを作成している際に浮かんだ疑問です。
疑問点
returnの部分(40行目~)について、
{todoNameRef}や、{handleAddTodo}には()がついていなくてもコンソールにエラーは出ないのですが、
{cntRemainTask()}には()をつけないとエラーが出てしまいます。
なぜなのでしょうか?
{cntRemainTask}とした際のエラー
react-dom.development.js:86 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
該当のソースコード
JavaScript
1import { useState, useRef } from 'react'; 2import TodoList from './TodoList.jsx'; 3import './App.css'; 4 5function App() { 6 7 const [todos, setTodos] = useState([]); 8 const [clickCnt, setCnt] = useState(0); 9 10 const todoNameRef = useRef(); 11 12 const click_cnt = () => { 13 setCnt(clickCnt + 1); 14 }; 15 16 17 const handleAddTodo = () => { 18 //タスクを追加する。 19 const name = todoNameRef.current.value; 20 if(name === '') return false; 21 click_cnt(); 22 setTodos((prevTodos) => { 23 return [...prevTodos, {id: clickCnt, name: name, completed: false}]; 24 }); 25 todoNameRef.current.value = null; 26 }; 27 28 const toggleTodo = (id) => { 29 const newTodos = [...todos]; 30 const todo = newTodos.find((todo) => todo.id === id); 31 console.log(todo); 32 todo.completed = !todo.completed; 33 setTodos(newTodos); 34 }; 35 36 const cntRemainTask = () => { 37 return todos.filter((todo) => !todo.completed).length; 38 }; 39 40 return ( 41 <> 42 <TodoList todos={todos} toggleTodo={toggleTodo} /> 43 <input type="text" ref={todoNameRef}/> 44 <button onClick={handleAddTodo}>タスクを追加</button> 45 <button>完了したタスクの削除</button> 46 <div>残りのタスク:{cntRemainTask()}</div> 47 </> 48 ); 49} 50 51export default App;
お手数ですが、ご回答のほうよろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/01/13 14:50