quiero pasar un argumento al método de clic de referencia usando javascript.
¿Qué estoy tratando de hacer?
hay una lista de tarjetas y cada tarjeta tiene más botones. Al hacer clic en el botón Más, se abriría un menú de selección con opciones para editar, cargar archivos y eliminar.
Ahora, al hacer clic en la opción Cargar archivo, el usuario debería permitir cargar el archivo para esa tarjeta.
a continuación se muestra el código,
const Parent = (data) => { const fileInput = React.useRef(null); const handleUploadClick = (id) => { console.log('id in here', id); //this is the correct id. meaning this is the id of the upload file button clicked for the card. fileInput.current?.click(); }, [fileInput.current]); return( <> {cardData.map(data, index) => { const {description, id } = data; console.log('id in map', id ) const uploadFile = ( <button onClick={() => handleUploadClick(id)}> Upload file </span> ) const edit = (//somelogic) const remove = (//some logic) const options = compact([edit, uploadFile, remove]); return ( <Card id={id} options={options} > <input type="file" ref={fileInput} style={display: 'none'} onChange={async () => { const file = fileInput?.current?.files?.[0]; try( const input = { file: file, } await updateFile({ variables: { id: id!, //here id is the id of the last card so it always uploads file for last card. but not the actual card for which the upload file button //clicked. input, }, }); </Card> </> ); }Ahora, el problema con el código anterior está en el método handleUploadclick, la identificación es correcta. sin embargo, el método handleUploadClick desencadena el clic del elemento input type="file". pero en el método onchange de este elemento input type="file", la identificación no es correcta. siempre es el id de la última tarjeta. y, por lo tanto, carga el archivo solo en la última tarjeta. lo que significa que pasa una identificación incorrecta al método updateFile en el método onchange de input type="file".
No estoy seguro de cómo pasar la identificación al método fileInput.current?.click() en handleUploadClick o hay alguna otra solución para solucionar este problema.
Podría alguien ayudarme con esto, por favor. Gracias.
en su caso, no debe usar useRef, todo lo que necesita hacer es usar useState y useEffect para manejar el cambio al pasar las claves correctamente, puede guardar el archivo después de que el usuario cargue el archivo usando la función onChange
const [file, setFile] = useState(null); const handleUploadClick = () => { console.log(file) } <button key={`button-${index}`} onClick={() => handleUploadClick()}> Upload file </button> <input type="file" key={`input-${index}`} ref={fileInput} style={display: 'none'} onChange={(e) => setFile(e.target.files[0])} />amigos, aquí está la respuesta a su pregunta, así que permítanme explicar primero lo que he hecho, a partir de su implementación, la ref no se mantiene, ya que está siendo reemplazada por cada elemento siguiente que devuelve en array.map() así que aquí vamos lo logramos todos los elementos de la matriz refs en una matriz itemsRef , de modo que cuando hacemos clic en el botón específico podemos obtener el elemento/entrada por su id.
import React from "react"; const inputs = [ { name: "Input one", id: 1 }, { name: "Input two", id: 2 } ]; const App = () => { // to hold all inputs refs const itemsRef = React.useRef([]); // to create an empty array of inputs lenght so we can hold refs later React.useEffect(() => { itemsRef.current = itemsRef.current.slice(0, inputs.length); }, []); // to triger clicked button relative input const handleUploadClick = React.useCallback( (id) => { console.log("id in here", id); //this is the correct id. meaning this is the id of the const eleByRefId = itemsRef?.current[id]; // ref by id eleByRefId && eleByRefId.click(); }, [itemsRef] ); // your file uploading logics here const handleFileChange = React.useCallback(async (e, id) => { const file = e.target.files[0]; // your file uploading logic // await updateFile({ // variables: { // id: id, // input, // }, // }); }, []); return ( <div style={{ display: "flex", flexDirection: "row" }}> {inputs.map((data, index) => { const { id, name } = data; return ( <div key={index} style={{ marginRight: 10 }}> <input type="file" key={id} ref={(el) => (itemsRef.current[id] = el)} // the magic part is happening here style={{ display: "none" }} onChange={(e) => handleFileChange(e, id)} /> <button onClick={() => handleUploadClick(id)}>{name}</button> </div> ); })} </div> ); }; export default React.memo(App);Aquí está la caja de códigos