Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Tratando de reformatear esta clase en una función

Estoy integrando una API de Twilio y quiero saber cómo puedo convertir esta clase en una función usando ganchos. He aprendido este método antes, pero es un poco complicado. Aquí está el código. El propósito de este código es que pueda enviar un mensaje de texto desde mi aplicación.

 import React, { Component } from 'react'; class TextForm extends Component { state = { text: { recipient: '', textmessage: '' } } sendText = _ => { const { text } = this.state; //pass text message GET variables via query string fetch(`http://localhost:4000/send-text?recipient=${text.recipient}&textmessage=${text.textmessage}`) .catch(err => console.error(err)) } render() { const { text } = this.state; const spacer = { margin: 8 } const textArea = { borderRadius: 4 } return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Welcome to React</h1> </header> <div style={{ marginTop: 10 }} > <h2> Send Text Message </h2> <label> Your Phone Number </label> <br /> <input value={text.recipient} onChange={e => this.setState({ text: { ...text, recipient: e.target.value } })} /> <div style={spacer} /> <label> Message </label> <br /> <textarea rows={3} value={text.textmessage} style={textArea} onChange={e => this.setState({ text: { ...text, textmessage: e.target.value } })} /> <div style={spacer} /> <button onClick={this.sendText}> Send Text </button> </div> </div> ); } } export default TextForm;
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Configurar un componente funcional

 const TextForm () => { const [text, setText] = React.useState({ { recipient: '', textmessage: '' } }); const sendText = ()=> { //pass text message GET variables via query string fetch(`http://localhost:4000/send-text?recipient=${text.recipient}&textmessage=${text.textmessage}`) .catch(err => console.error(err)) } const spacer = { margin: 8 } const textArea = { borderRadius: 4 } return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Welcome to React</h1> </header> <div style={{ marginTop: 10 }} > <h2> Send Text Message </h2> <label> Your Phone Number </label> <br /> <input value={text.recipient} onChange={e => setText({ text: { ...text, recipient: e.target.value } })} /> <div style={spacer} /> <label> Message </label> <br /> <textarea rows={3} value={text.textmessage} style={textArea} onChange={e => setText({ text: { ...text, textmessage: e.target.value } })} /> <div style={spacer} /> <button onClick={sendText}> Send Text </button> </div> </div> ); } export default TextForm
about 4 years ago · Juan Pablo Isaza Report

0

La mayoría de las partes están ahí, solo tienes que organizarlas. Ya no tiene que depender de this : simplemente puede agregar funciones dentro del componente para manejar las cargas y los cambios de estado.

(Nota: agregué algunos conjuntos de campos a su JSX porque creo que se ven bien).

 const { useState } = React; function TextForm() { // Set up the state with an empty object const [text, setText] = useState({}); // I'm only logging the state here as I don't have // API access for this working demo function sendText() { console.log(text); // const params = `${text.phonenumber}&textmessage=${text.message}`; // fetch(`http://localhost:4000/send-text?${params}`) // .catch(err => console.error(err)) } // Grab the name and value from the input // that has been clicked, and use that information // to update the state function handleChange(e) { const { name, value } = e.target; setText({ ...text, [name]: value }); } // Make sure that for each input you include // a name attribute return ( <div> <fieldset> <legend>Phone Number</legend> <input name="phonenumber" type="tel" value={text.phonenumber} onChange={handleChange} /> </fieldset> <fieldset> <legend>Message</legend> <textarea name="message" rows={3} value={text.message} onChange={handleChange} /> </fieldset> <br /> <button onClick={sendText}>Send Text</button> </div> ); } ReactDOM.render( <TextForm />, document.getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

about 4 years ago · Juan Pablo Isaza Report

0

primero para el componente funcional si desea crear un state , necesita importar useState desde react , luego convierta su estado primero:

de esto:

 state = { text: { recipient: '', textmessage: '' } }

A este componente funcional useState

 const [text, setText] = useState({ recepient: "", textMessage: "" });

convierte tu método en función a partir de esto:

 sendText = _ => { const { text } = this.state; //pass text message GET variables via query string fetch(`http://localhost:4000/send-text?recipient=${text.recipient}&textmessage=${text.textmessage}`) .catch(err => console.error(err)) } render() { const { text } = this.state; const spacer = { margin: 8 } const textArea = { borderRadius: 4 }

A esta función:

 const sendText = (_) => { //pass text message GET variables via query string fetch( `http://localhost:4000/send-text?recipient=${text.recepient}&textmessage=${text.textMessage}` ).catch((err) => console.error(err)); }; const spacer = { margin: 8 }; const textArea = { borderRadius: 4 };

y luego convierta su devolución, el código completo está a continuación:

 import React, { useState } from "react"; const TextForm = () => { const [text, setText] = useState({ recepient: "", textMessage: "" }); const sendText = (_) => { //pass text message GET variables via query string fetch( `http://localhost:4000/send-text?recipient=${text.recepient}&textmessage=${text.textMessage}` ).catch((err) => console.error(err)); }; const spacer = { margin: 8 }; const textArea = { borderRadius: 4 }; return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Welcome to React</h1> </header> <div style={{ marginTop: 10 }}> <h2> Send Text Message </h2> <label> Your Phone Number </label> <br /> <input value={text.recepient} onChange={(e) => setText((prevText) => ({ ...prevText, recepient: e.target.value })) } /> <div style={spacer} /> <label> Message </label> <br /> <textarea rows={3} value={text.textMessage} style={textArea} onChange={(e) => setText((prevText) => ({ ...prevText, textMessage: e.target.value })) } /> <div style={spacer} /> <button onClick={sendText}> Send Text </button> </div> </div> ); }; export default TextForm;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!