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)}}/>
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)}}/>
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> );