传递道具 - React

Passing props - React

我有一个问题,我已经被困了几个小时了。

我有一个组件,当它被触发时,它会将 const 从“true”更改为“false”。使用此信息,我想在另一个组件中显示“已发送”或“未发送”文本 div。

为了我的生活,我无法将此道具传递给其他组件。

我无法获取组件 ReadOnlyRow 来读取 sentStatus 属性。

import React, { useState } from "react";


const TextForm = ({ contact, messageSent, props }) => {
  
  const [sentStatus, setSentStatus] = useState(true)
  const [sendTextText, setSendTextText] = useState("N/A")

  function sendText () {

    let phoneNumber = 1 + contact.phoneNumber
    
    //pass text message GET variables via query string
    fetch(`http://localhost:4000/send-text?recipient=${phoneNumber}&textmessage=Dear ${contact.fullName}, Your liscnese is set to expre on 9/21`)
    .catch(err => console.error(err))
    console.log(contact.fullName)
    console.log(messageSent)
    
    console.log(sentStatus)
    setSentStatus(!sentStatus)
    
    if (sentStatus === true){
      setSendTextText('good')
      console.log("true")
    } else {
      setSendTextText('bad')
      console.log("false")
    }
    }


  return (
    <div>
    <button onClick={sendText}>Send</button>
    <h1>{contact.phoneNumber}</h1>
    </div>
    
  );
};

export default TextForm;

import React, { useState, Fragment, Component } from "react";
import { nanoid } from "nanoid";
import "./App.css";
import data from "./mock-data.json";
import ReadOnlyRow from "./components/ReadOnlyRow";
import EditableRow from "./components/EditableRow";
import Header from "./components/Header";
import TextForm from "./TextForm";

function App() {
  const [contacts, setContacts] = useState(data)
  const [messageSent, setMessageSent] = useState(12)
  
  const [addFormData, setAddFormData] = useState({
    fullName: "",
    address: "",
    phoneNumber: "",
    email: ""
  });
  

  // const [textItem, setSet] = useState({
  //   text: {
  //     recipient: 'gorge',
  //     textmessage: 'gorgeous'
  //   }
  // })

  

  const [editFormData, setEditFormData] = useState({
    fullName: "",
    address: "",
    phoneNumber: "",
    email: "",
  });

  const [editContactId, setEditContactId] = useState(null);

  const handleAddFormChange = (event) => {
    event.preventDefault();

    const fieldName = event.target.getAttribute("name");
    const fieldValue = event.target.value;

    const newFormData = { ...addFormData };
    newFormData[fieldName] = fieldValue;

    setAddFormData(newFormData);
  };
  

  const handleEditFormChange = (event) => {
    event.preventDefault();
    

    const fieldName = event.target.getAttribute("name");
    const fieldValue = event.target.value;

    const newFormData = { ...editFormData };
    newFormData[fieldName] = fieldValue;

    setEditFormData(newFormData);

    
  };

  const handleAddFormSubmit = (event) => {
    event.preventDefault();

    const newContact = {
      id: nanoid(),
      fullName: addFormData.fullName,
      address: addFormData.address,
      phoneNumber: addFormData.phoneNumber,
      email: addFormData.email,
    };

    const newContacts = [...contacts, newContact];
    setContacts(newContacts);
  };

  const handleEditFormSubmit = (event) => {
    event.preventDefault();

    const editedContact = {
      id: editContactId,
      fullName: editFormData.fullName,
      address: editFormData.address,
      phoneNumber: editFormData.phoneNumber,
      email: editFormData.email,
    };

    const newContacts = [...contacts];

    const index = contacts.findIndex((contact) => contact.id === editContactId);

    newContacts[index] = editedContact;

    setContacts(newContacts);
    setEditContactId(null);
  };

  const handleEditClick = (event, contact) => {
    event.preventDefault();
    setEditContactId(contact.id);

    const formValues = {
      fullName: contact.fullName,
      address: contact.address,
      phoneNumber: contact.phoneNumber,
      email: contact.email,
    };

    setEditFormData(formValues);
  };

  const handleCancelClick = () => {
    setEditContactId(null);
  };

  const handleDeleteClick = (contactId) => {
    const newContacts = [...contacts];

    const index = contacts.findIndex((contact) => contact.id === contactId);

    newContacts.splice(index, 2);

    setContacts(newContacts);
  };
  
  function status ({sentStatus}) {
    console.log(sentStatus)
  }

  
    return (
    <div className="app-container">
      <Header />
      <form onSubmit={handleEditFormSubmit}>
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Guard #</th>
              <th>Phone Number</th>
              <th>Employee ID</th>
              <th>Expiration Date</th>
              <th>Actions</th>
              <th>Was the text sent out?</th>
              <th>Was an SMS sent?</th>
            </tr>
          </thead>
          <tbody>
            {contacts.map((contacto) => (
              <Fragment>
                {editContactId === contacto.id ? (
                  <EditableRow
                    editFormData={editFormData}
                    handleEditFormChange={handleEditFormChange}
                    handleCancelClick={handleCancelClick}
                  />
                ) : (
                  <ReadOnlyRow
                    contact={contacto}
                    handleEditClick={handleEditClick}
                    handleDeleteClick={handleDeleteClick}
                    messageSent={messageSent}
                  />
                )}
              </Fragment>
            ))}
          </tbody>
        </table>
      </form>

      <h2>Add a Contact</h2>
      <form onSubmit={handleAddFormSubmit}>
        <input
          type="text"
          name="fullName"
          required="required"
          placeholder="Enter a name..."
          onChange={handleAddFormChange}
        />
        <input
          type="text"
          name="address"
          required="required"
          placeholder="Enter an addres..."
          onChange={handleAddFormChange}
        />
        <input
          type="text"
          name="phoneNumber"
          required="required"
          placeholder="Enter a phone number..."
          onChange={handleAddFormChange}
        />
        <input
          type="email"
          name="email"
          required="required"
          placeholder="Enter an email..."
          onChange={handleAddFormChange}
        />
        <button type="submit">Add</button>
      </form>
    </div>
  );
};

export default App;
import React, { useState } from "react";
import TextForm from "../TextForm";
import WasMessageSent from "./WasMessageSent";
import TextStatus from "./TextStatus";
import App from "../App";

const ReadOnlyRow = ({ contact, handleEditClick, handleDeleteClick, sentStatus, messageSent, sendo}, props) => {
  
  const [text, setText] = useState("yes")


  function status (){
    const gord = {sentStatus}
    console.log(gord)

  }

  

  return (
    <tr>
      <td>{contact.fullName}</td>
      <td>{contact.address}</td>
      <td>{contact.phoneNumber}</td>
      <td>{contact.email}</td>
      <td>
        <button
          type="button"
          onClick={(event) => handleEditClick(event, contact)}
        >
          Edit
        </button>
        <button type="button" onClick={() => handleDeleteClick(contact.id)}>
          Delete
        </button>
      </td>
      <td>
        <TextForm 
        contact={contact}
        status={sentStatus}
        />
        <button>Send Email</button>
      </td>
      <td>Did they update it yet?</td>
      <td>{messageSent}</td>
      <td>{text}</td>
      <td><button onClick={status}>statuschecker</button></td>
    </tr>
  );
};

export default ReadOnlyRow;

这是一个关于如何做到这一点的例子,

您在父应用程序中创建一个状态,然后将状态传递给需要它的子组件 (ReadOnlyRow),然后将 setState 传递给另一个子组件 (TextForm)

这是一个简单的演示,希望它能帮助你更好地理解我:

应用组件

import React, { useState } from "react";

import ReadOnlyRow from "./ReadOnlyRow";
import TextForm from "./TextForm";

function App() {
 
  const [sentStatus, setSentStatus] = useState(false)

  return (
    <div className="app-container">
     <TextForm setSentStatus={setSentStatus} />
     <ReadOnlyRow sentStatus={sentStatus} />
    </div>
  );
};

export default App;

TextForm 组件

import React from "react";

const TextForm = ({ setSentStatus }) => {
  
  const sendText = () => {
    setSentStatus(true)
  }

  return (
    <div>
      <button onClick={sendText}>Send</button>
    </div>
  );
};

export default TextForm;

ReadOnlyRow 组件

import React from "react";

const ReadOnlyRow = ({ sentStatus }) => {

  return (
   <p>
      {sentStatus ? 'sent' : 'not sent'}
   </p>
  );
};

export default ReadOnlyRow;