【问题标题】:TypeError: props.onAdd is not a function ReactTypeError:props.onAdd 不是 React 函数
【发布时间】:2021-07-11 02:36:52
【问题描述】:

我的 React 应用程序中定义的道具出现“不是函数”错误。

我尝试添加onAdd={() => addTodo()},但是没有成功。

我想知道错误发生的原因以及如何修复错误。

请看error picture

TodoForm.js - 我接受道具的地方

import React, {useState} from 'react';

const TodoForm = (props) => {

    const [input, setInput] = useState('');

    const handleSubmit = e => {
    
    // console.log(e);
    e.preventDefault();
    
    props.onAdd({
        id: Math.floor(Math.random() * 10000),
        text: input
    });
    setInput('');
};

return(
    <div>
        <form onSubmit={handleSubmit}>
            <input type="text"
             placeholder="Add a todo"
              value={input} name="text"
               className='todo-input' 
               onChange={e => setInput(e.target.value)} />
                <input type="submit" value="Add todo"></input>
            
        </form>
    </div>
);
}
export default TodoForm;

TodoList.js

import React, { useState } from 'react';
import TodoForm from './TodoForm';

const TodoList = () => {
   const [todos, setTodos] = useState([]);

   const addTodo = todo => {
       if(!todo.text || /^\s*$/.test(todo.text)){
           return;
       }

       const newTodos = [todo, ...todos];

       setTodos(newTodos);
       console.log(...todos);
       console.log("is working");
   }

   return(
       <div>
           <h1>Waht's the plan for today?</h1>
           <TodoForm onAdd={() => addTodo()} />
       </div>
   );
}

export default TodoList;

【问题讨论】:

    标签: javascript html reactjs rxjs react-hooks


    【解决方案1】:

    确保您保存文件,有问题,您的代码应该仍然可以工作,而不是您希望它如何工作,但它应该可以工作,但是 Sean 提供的解决方案是 100% 正确的。 “onAdd={() =&gt; addTodo()},然而,它不起作用。”在这里,您只需创建一个返回函数的函数。

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 2018-12-23
      • 2023-03-27
      • 2020-09-11
      • 2021-07-20
      • 2016-11-21
      • 2020-12-04
      • 2015-09-01
      • 2015-08-22
      相关资源
      最近更新 更多