【问题标题】:How to solve the error "this.props.myFunction" is not a function in react?如何解决错误“this.props.myFunction”不是反应中的函数?
【发布时间】:2019-08-30 13:12:50
【问题描述】:

我有一个包含两个组件的反应应用程序。我的子组件有一个包含一些记录的表。每条记录都有一个按钮,我在 onclick 中调用一个带有参数(id)的函数(editUser)。在那个函数中,我通过 props 将该 id 发送到 Parent 组件。该函数已在构造函数中绑定。但是当按钮点击时,控制台说 this.props.userId is not a function

子组件:

class UsersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
        this.editUser = this.editUser.bind(this);

    }

    editUser(id) {
       this.props.userId(id);
    }

    render() {
        return (
        <TableBody>
            {data
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map(n => {
                    return (
                        <TableRow key={n.id}>
                            <TableCell className={classes.fixedTd}>
                                <BorderColorIcon onClick={() => this.editUser(n.userId)} className="action margin-r" />
                            </TableCell>
                        </TableRow>
                    );
                })}
        </TableBody>
        );
    }
}

export UsersTable;

父组件:

class CompanyUserMgt extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    editUser = (id) => {
        console.log("user", id)
    }


    render() {
        return (
            <div className="">
        <UsersTable
            userId={this.editUser}
                    key={this.state.tableKey}
                />
            </div>
        )
    }
}

export default CompanyUserMgt;

我该如何解决这个问题?

【问题讨论】:

  • 事情对我来说是正确的。我的建议是,尝试记录 this 并检查它显示的内容。我的假设是上下文在某处丢失了
  • 一切正常。你是如何在BorderColorIcon 中呼叫onClick 的?
  • 您是否确保在类中正确转换箭头函数?您是否尝试以常规方式声明 editUser?
  • @DoğancanArabacı 是的,我也尝试过常规方式。但它不起作用

标签: javascript reactjs


【解决方案1】:

我认为你可以简化一些事情,你可以在你的子组件上尝试下面的代码吗?

class UsersTable extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };

    }

    render() {
        return (
        <TableBody>
            {data
                .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                .map(n => {
                    return (
                        <TableRow key={n.id}>
                            <TableCell className={classes.fixedTd}>
                                <BorderColorIcon onClick={() => this.props.userId(n.userId)} className="action margin-r" />
                            </TableCell>
                        </TableRow>
                    );
                })}
        </TableBody>
        );
    }
}

export UsersTable;

【讨论】:

  • 成功了!谢谢。但仍然不知道为什么该功能不起作用
  • 很可能是因为这一行 this.editUser = this.editUser.bind(this);试图将箭头函数绑定到对象函数
猜你喜欢
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 2020-08-05
相关资源
最近更新 更多