I have two components.
I send showModalDelete method in my parent component as promp to my child element.
import * as React from 'react';
import Table from './../components/Table';
import Delete from './../components/Delete';
class User extends React.Component<any, any> {
static urlUsers : string = 'http://localhost:52968/employee/api/index';
static urlDelete : string = 'http://localhost:52968/employee/api/delete/';
static tableHeader = ['Id','First name', 'Surname','Email','Phone number',''];
static columns = ['id','firstName', 'lastName','email','phoneNumber'];
private delete: any;
constructor( props: any) {
super(props);
this.state = { users: []};
console.log(this);
this.showModalDelete.bind(this);
}
componentWillMount() {
}
showModalDelete() {
console.log(this);
this.delete.handleShow();
}
render() {
console.log(this);
return (
<div>
<Table
show={this.showModalDelete}
url={User.urlUsers}
header={User.tableHeader}
columns={User.columns}
/>
<Delete ref={(del) => { this.delete = del; }} />
</div>
);
}
}
export default User;
Then in my child component a define onClick method to call parrent method. (this.props.show)
import * as React from 'react';
import * as $ from 'jquery';
class Table extends React.Component<any,any> {
constructor(props: any) {
super(props);
this.state = { items: []};
}
componentWillMount() {
this.loadItems();
}
loadItems() {
var self: Table;
self = this;
$.ajax (
{
url: self.props.url,
dataType: 'json',
cache:false,
success:
function(items: any) {
self.setState({items:items});
},
error: function(xhr: any, status: any, err: any) {
console.log(xhr);
}
});
}
render() {
return (
<table className="table row-border stripe no-footer">
<thead>
<tr>
{
this.props.header.map((item:string,index: number) =>
<th key={index}>{item}</th>
)
}
</tr>
</thead>
<tbody>
{
this.state.items.map((item:any) =>
<tr key={item.id}>
{
this.props.columns.map((column:string,index: number) =>
<td key={index}>{item[column]}</td>
)
}
<td>
<a
onClick={this.props.show}
className="glyphicon glyphicon-trash table-buttons table-buttons-delete"
/>
</td>
</tr>
)
}
</tbody>
</table>
);
}
}
export default Table;
When show modal delete is called, this is undefined. What am I doing wrong? Iam little confused how to use this in typescript. Thanks for any help.
The .bind
method will return a new function that has a bound this
. It does not mutate the function you call it on. So your constructor bind doesn't re-assign the method, so it's as if you had never called bind at all.
To fix this all you have to do is re-assign the method when you call bind:
this.showModalDelete = this.showModalDelete.bind(this);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.