【问题标题】:react-data-components renders component (a button) but can't access state or function defined outside the render methodreact-data-components 渲染组件(按钮),但无法访问在渲染方法之外定义的状态或函数
【发布时间】:2018-09-09 01:07:21
【问题描述】:

我正在使用 react-data-components 来呈现表格。在表格内,我呈现了一个删除按钮。但是,在 render 方法中,它无法访问“this”关键字,因此无法访问按钮单击时的任何处理函数。我知道如何在父组件和子组件之间进行通信,但这似乎不属于该类别。代码编译但在运行时失败。错误是:未捕获的类型错误:无法读取未定义的属性“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;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这里有 2 个选项。

    1.- 调用handleClick作为箭头函数,绑定函数。

    onClick={() => this.handleClick()}
    

    或 2.- 在构造函数中绑定函数:

    constructor(props: MyComponentProps, context: object) {
        super(props, context);
        this.handleClick = this.handleClick.bind(this);
    }
    

    决定权在你,我使用第二个 when 是多次调用的函数,第一个 when 是一次性函数。

    【讨论】:

    • 您需要使用您想要访问上下文的所有功能进行绑定,所以我认为您也需要这样做:this.renderLink = this.renderLink.bind(this);。
    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2018-04-12
    • 2018-06-03
    • 2018-01-08
    相关资源
    最近更新 更多