将函数作为 prop 传递不起作用(反应)

问题描述 投票:0回答:1

我正在尝试调用从App.js 传递到AddNote.js 的handleAddNote,但我无法在AddNote 中引用它,而不会收到错误消息,提示handleAddNote 不是函数。我尝试了多种方法,但我总是发现它不是一个函数或未定义。在教程中,我遵循它说只需在handleSave函数中调用handleAddNote(noteText),但我无法这样做。

import Note from './Components/Note';
import NotesList from './Components/NotesList';
import { useState } from 'react';
import { nanoid } from 'nanoid';


const App = () => {

  const[notes, setNotes] = useState([
    {
      id: nanoid(),
      text: "My first note",
      date: "2/12/2024"
    },
    {
      id: nanoid(),
      text: "My second note",
      date: "2/13/2024"
    },
    {
      id: nanoid(),
      text: "My third note",
      date: "2/14/2024"
    },
    {
      id: nanoid(),
      text: "My fourth note",
      date: "2/15/2024"
  }])

  const addNote = (text) => {
        console.log(text);
  }

  return (
    <div className="container">
      <NotesList notes={notes} handleAddNote={addNote}/>
    </div>

  );
}

export default App;
import Note from './Note';
import AddNote from './AddNote';

const NotesList = ({ notes, handleAddNote }) => {
    return (
        <div className="notes-list">
            {notes.map((note)=> 
                <Note id={note.id} text={note.text} date={note.date}/>
            )}

            <AddNote handleAddNote={handleAddNote}/>
        </div>
    );
}

export default NotesList;
import { useState } from 'react';

const AddNote = ({ handleAddNote }) => {
    const [noteText, setNoteText] = useState("");

    const handleChange = (event) => {
        setNoteText(event.target.value);
    };

    const handleSave = () => {
        console.log({handleAddNote});
        {handleAddNote(noteText)};
    };

    return(
        <div className="note new">
            <textarea 
                onChange={handleChange}
                value={noteText}
                className='new-note'
                rows="8" 
                columns="10" 
                placeholder="Type to add a note...">
            </textarea>

            <div className="note-footer">
                <small>200 remaining</small>
                <button className='save' onClick={(noteText)=>handleAddNote(noteText)}>Save</button>
            </div>
        </div>

    );
}

export default AddNote

reactjs onclick hook react-props
1个回答
0
投票

从上面的代码来看,函数似乎已正确传递给子组件。

去掉大括号

{handleAddNote(noteText)}
;从handleSave函数只需使用
handleAddNote(noteText);
它应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.