我正在使用react-data-components来呈现表 . 在表格内我渲染一个删除按钮 . 但是,在render方法中,它无法访问“this”关键字,因此无法在按钮单击时访问任何处理函数 . 我知道如何在父组件和子组件之间进行通信,但这似乎不属于该类别 . 代码编译但在运行时失败 . 错误是:未捕获TypeError:无法读取属性'handleClick'未定义任何帮助表示赞赏 .
这是我的代码:
接口MyComponentProps扩展RouteComponentProps {
appState: AppState;
}
@Inject( 'APPSTATE')
class MyComponent扩展了React.Component {
constructor(props: MyComponentProps, context: object) {
super(props, context);
}
renderLink(val: any, row: any) {
console.log(this); //'this' is undefined
return (
<button onClick={this.handleClick}>Delete</button>
);
}
handleClick() {
console.log('click');
// access appState here
}
render() {
var columns =
[
{ title: '', prop: 'Id', render: this.renderLink },
{ title: 'Name', prop: 'Name' }
];
let data = [];
// code to populate data
return (<DataTable keys="fileId" columns={columns} initialData={data} />);
}
}
导出默认MyComponent;
1 回答
你有两个选择 .
1.-调用handleClick作为箭头函数,绑定函数 .
或2.-在构造函数中绑定函数:
决定是你的,我使用第二个是多次调用的函数,第一个是一次性函数 .