gpt4 book ai didi

javascript - 通过函数传递 props 时无法读取未定义的属性 'saveUpload'

转载 作者:行者123 更新时间:2023-12-03 02:57:16 26 4
gpt4 key购买 nike

var Admin = React.createClass({
saveUpload: function(id) {
alert(id);
},

getInitialState() {
return {
uploads: []
};
},

componentDidMount() {
var self = this;
$.ajax({
url: 'http://localhost:8080/admin/uploads',
success: function(data) {
self.setState({
uploads: data
})
}
});
},

render: function() {
var obj = this.state.uploads.map(function(product) {
return (
<Uploads product = {product}
saveHandle = {this.saveUpload}
/>
)
});

return (
< div >
<div className = "container" >
<br / >
<h1 className = "text-center" > Welcome Admin < /h1>
<br / > < br / >
<hr / >
</div>
<h3 className = "text-center" > Company Upload Details < /h3>
<div className = "container" >

<table className = "table" >
<thead className = "thead-light" >
<tr >
<th > Id < /th> <th > CompanyName < /th>
<th > Date & Time < /th> <
th > FileName(csv) < /th> <
th > Size(KB) < /th> <
th > Status < /th> <
/tr> <
/thead> {
obj
} <
/table>
</div> </div>
)
}
});

这是上传组件

var Uploads = React.createClass({
show() {
this.props.saveHandle(this.props.product.id);
},
render() {
return (
<tr>
<td> {this.props.product.id} </td>
<td> {this.props.product.company.companyName} </td>
<td> {(new Date(this.props.product.date)).toString()} </td>
<td> {this.props.product.fileName} </td>
<td> {this.props.product.filesize} </td>
<td> {this.props.product.status} </td>
<td>
<button className = "button" onClick = {this.show}> Save </button>
</td>
</tr>
)
}
});

这是我的代码,当单击保存按钮时,我将 id 从上传组件传递到管理组件,但它给了我一个错误,表明 saveUpload 未定义。我很困惑,它给了我这个错误,我在管理组件中有一个函数 saveUpload 。这段代码有什么问题

最佳答案

错误在这里:

var obj = this.state.uploads.map(function(product) {
return (
<Uploads product = {product}
saveHandle = {this.saveUpload}
/>
)
});

map()内部,this不再是Admin组件的实例,它是window >。如果你像这样绑定(bind)它:

var obj = this.state.uploads.map(function(product) {
return (
<Uploads product = {product}
saveHandle = {this.saveUpload}
/>
)
}.bind(this));

然后 this 将指向 Admin 实例,您应该获得您期望的功能。如果你有ES6,你也可以这样写:

var obj = this.state.uploads.map(product =>
<Uploads product = {product}
saveHandle = {this.saveUpload}
/>);

使用“粗箭头”=> lambda 表达式,this 会自动绑定(bind)到内部的封闭范围,从而节省您的一些精力。

关于javascript - 通过函数传递 props 时无法读取未定义的属性 'saveUpload',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com