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

344
Views
¿Cómo exportar la variable del componente de reacción?

Estoy usando Mantine para una barra de búsqueda y necesito obtener el número de palabras del área de texto. Esto está usando Nodejs y React. Necesito poder exportar este valor para usarlo en un archivo diferente.

 import React, { useState } from 'react'; import { TextInput, createStyles } from '@mantine/core'; var count = document.getElementById('count'); const useStyles = createStyles((theme, { floating }: { floating: boolean }) => ({ root: { position: 'relative', }, label: { position: 'absolute', zIndex: 2, top: 7, left: theme.spacing.sm, pointerEvents: 'none', color: floating ? theme.colorScheme === 'dark' ? theme.white : theme.black : theme.colorScheme === 'dark' ? theme.colors.dark[3] : theme.colors.gray[5], transition: 'transform 150ms ease, color 150ms ease, font-size 150ms ease', transform: floating ? `translate(-${theme.spacing.sm}px, -28px)` : 'none', fontSize: floating ? theme.fontSizes.xs : theme.fontSizes.sm, fontWeight: floating ? 500 : 400, }, required: { transition: 'opacity 150ms ease', opacity: floating ? 1 : 0, }, input: { '&::placeholder': { transition: 'color 150ms ease', color: !floating ? 'transparent' : undefined, }, }, } ) ); export function FloatingLabelInput() { const [focused, setFocused] = useState(false); const [value, setValue] = useState(''); const { classes } = useStyles({ floating: value.trim().length !== 0 || focused }); const uniqueid = "input"; return( <TextInput id={ uniqueid } placeholder="Add anything you want to the book of the internet." required classNames={classes} value={value} onChange={(event) => setValue(event.currentTarget.value)} onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} mt="md" onKeyUp={(e) => { var text = value.split(' '); var wordcount = 0; for (var i = 0; i < text.length; i++) { if (text[i] !== ' ') { wordcount++; } } count.innerText = wordcount; } } autoComplete="nope" /> ); }

Como puede ver, lo envía correctamente a html, pero regresar dentro de la función no funciona en absoluto.

Intenté exportarlo, intenté devolverlo a la función pero no lo ve. Intenté exportar y usar las exportaciones de módulos, pero eso tampoco funciona. Cualquier ayuda sería apreciada.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En el siguiente fragmento de código, mi componente raíz (llamado App) es responsable de mantener el estado de la aplicación, pero puede otorgar cualquier estado a cualquiera de sus elementos secundarios. También puede dar modificadores de estado (funciones setX ) a sus hijos, que es lo que estoy demostrando aquí:

 function Input ({ setWordCount }) { function updateWordCount (event) { setWordCount(event.target.value.split(' ').length) } return <input type="text" onKeyUp={updateWordCount} /> } function SomeOtherComponent ({ count }) { return ( <span>: {count} words</span> ) } function App () { const [wordCount, setWordCount] = React.useState(0) return ( <p> <Input setWordCount={setWordCount} /> <SomeOtherComponent count={wordCount} /> </p> ) } ReactDOM.render(<App />, document.getElementById('app'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.5/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.5/umd/react-dom.production.min.js"></script> <div id="app" />

Como puede ver, el componente Input puede llamar a la función setWordCount proporcionada por su padre para cambiar un estado. Luego, el padre (aplicación) puede dar ese estado a cualquier número de sus hijos. Cada componente también puede vivir en un archivo separado, esto aún funcionaría...

No estoy seguro de haber entendido su pregunta correctamente, pero con suerte, esto puede darle ideas que puede reutilizar en su propio código.

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!