Estoy tratando de involucrar la codificación de un componente simple para resaltar subcadenas de texto proporcionadas por un usuario
pero recibo errores cuando intento obtener el valor de un área de texto y compararlo con un área de entrada
import React from "react"; const Highlighted = ({ text = "", highlight = "" }) => { if (!highlight.trim()) { return <span>{text}</span>; } const regex = new RegExp(`(${highlight})`, "gi"); const parts = text.split(regex); return ( <span> {parts.filter(String).map((part, i) => { return regex.test(part) ? ( <mark key={i}>{part}</mark> ) : ( <span key={i}>{part}</span> ); })} </span> ); }; const App = () => { const text = <textarea data-testid="source-text" />; const highlight = <input data-testid="search-term" />; return ( <> <Highlighted text={text} highlight={highlight} /> </> ); }; export default App;const text = <textarea data-testid="source-text" />; const highlight = <input data-testid="search-term" />;No puede obtener valores directamente de JSX.
En lugar de hacer eso, puede configurar useState para esas variables (como estados) y usar onChange en estos campos de entrada para actualizar los estados con valores de entrada.
const Highlighted = ({ text = "", highlight = "" }) => { if (!highlight.trim()) { return <span>{text}</span>; } const regex = new RegExp(`(${highlight})`, "gi"); const parts = text.split(regex); return ( <span> {parts.filter(String).map((part, i) => { return regex.test(part) ? ( <mark key={i}>{part}</mark> ) : ( <span key={i}>{part}</span> ); })} </span> ); }; const App = () => { const [text, setText] = React.useState('') const [highlight, setHighlight] = React.useState('') return ( <div> <textarea data-testid="source-text" onChange={(event) => setText(event.target.value)}/> <input data-testid="search-term" onChange={(event) => setHighlight(event.target.value)}/> <Highlighted text={text} highlight={highlight} /> </div> ); }; ReactDOM.render( <App/>, document.getElementById("root") ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script> <div id="root"></div>