• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

112
Views
Pase un controlador de clase a componente en bucle

Quiero pasar un identificador de clic (handleDeleteUser) a otro componente, desde user.js a DropDownUserTool.js en realidad:

Usuario.js

 handleDeleteUser = (id) => { alert(id); }; ... // in render User.data.map(function (User, i) { return ( <DropDownUserTool id={User.id} click={(e) => { this.handleDeleteUser(e); }} /> ); });

DropDownUserTool.js

 const DropDownUserTool = (props) => { return ( <ButtonDropdown isOpen={dropdownOpen} toggle={toggle}> <DropdownToggle color="secondary" caret> tools </DropdownToggle> <DropdownMenu> <DropdownItem> <Link to={"/User/Edit/" + props.id}>Edit</Link> </DropdownItem> <DropdownItem onClick={() => props.click(props.id)}> Delete </DropdownItem> </DropdownMenu> </ButtonDropdown> ); };

Pero después de hacer clic devuelve un error:

TypeError: no se pueden leer las propiedades de undefined (leyendo 'handleDeleteUser')

En esta línea:

<DropDownUserTool id={User.id} click={(e) => {this.handleDeleteUser(e)}}/>

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Usted está tratando de llegar a this map interior, ¡simplemente this ! render interior antes del bucle:

 let realthis = this;

Luego llame a su controlador de esta manera:

 <DropDownUserTool id={User.id} click={(e) => {realthis.handleDeleteUser(e)}}/>
almost 3 years ago · Juan Pablo Isaza Report

0

Cuando está haciendo su mapa, está usando una llamada de función estándar y está perdiendo su contexto. Utilice una función de flecha en su lugar.

 class User extends React.Component { constructor(props) { super(props); this.state = { data: [{ id: 1 }, { id: 2 }, { id: 3 }] }; } handleDeleteUser = (id) => alert(id); render() { return ( <div> // this needs to be an arrow function // that way you won't change the context of `this` {this.state.data.map((item, i) => { return ( <DropDownUserTool id={item.id} key={item.id} handleDelete={this.handleDeleteUser } /> ); })} </div> ); } } const DropDownUserTool = ({ handleDelete, id }) => ( <button onClick={() => handleDelete(id)}>Delete</button> );
almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error