Javascript 在React.js中映射时引用道具时出现问题
所以我的问题是我得到了这个错误: 未捕获的TypeError:无法读取未定义的属性“removeCard” 根据该代码:Javascript 在React.js中映射时引用道具时出现问题,javascript,reactjs,Javascript,Reactjs,所以我的问题是我得到了这个错误: 未捕获的TypeError:无法读取未定义的属性“removeCard” 根据该代码: var SurveyDiv = React.createClass({ getInitialState: function() { return{ showCard: true }; }, render: function() { console.log(this.props.routes); var routesObj
var SurveyDiv = React.createClass({
getInitialState: function() {
return{
showCard: true
};
},
render: function() {
console.log(this.props.routes);
var routesObject = this.props.routes;
var itemSurvey = this.state.showCard ? this.props.questions.map(function (itemSurvey) {
return(
<Card
id ={itemSurvey.surveyID}
title={itemSurvey.title}
options={itemSurvey.options}
type={itemSurvey.type}
routes={routesObject}
removeHandler={this.removeCard}>
</Card>
);
}) : '';
return(
<div className="surveyDiv">
{itemSurvey}
</div>
);
},
removeCard: function() {
console.log("inside removeCard");
this.setState({showCard: false});
}
});
var SurveyDiv=React.createClass({
getInitialState:函数(){
返回{
展示卡:对
};
},
render:function(){
console.log(this.props.routes);
var routeObject=this.props.routes;
var itemSurvey=this.state.showCard?this.props.questions.map(函数(itemSurvey){
返回(
);
}) : '';
返回(
{itemSurvey}
);
},
removeCard:function(){
控制台日志(“内部移除卡”);
this.setState({showCard:false});
}
});
所以我的理论是,当我在里面说这个.removeCard时,它引用的是var itemSurvey,而不是实际上包含removeCard函数的SurveyDiv。我怎样才能避开这件事 您应该能够在地图之外声明它并将其传入
// in render()
var removeCard = this.removeCard.bind(this);
// inside <Card
removeHandler: {removeCard}
//在render()中
var removeCard=this.removeCard.bind(this);
//内部当您使用来this.removeCard
在函数内部时,您所引用的此
是函数而不是SurveyDiv
您可以通过以下几种方式解决此问题:
var removeCard = this.removeCard;
var itemSurvey = this.state.showCard ? this.props.questions.map(function (itemSurvey) {
return(
<Card
id ={itemSurvey.surveyID}
title={itemSurvey.title}
options={itemSurvey.options}
type={itemSurvey.type}
routes={routesObject}
removeHandler={removeCard}>
</Card>
);
}) : '';
很抱歉,引用了一个函数。您的第一个示例非常有用,非常感谢!
var itemSurvey = this.state.showCard ? this.props.questions.map(function (itemSurvey) {
return(
<Card
id ={itemSurvey.surveyID}
title={itemSurvey.title}
options={itemSurvey.options}
type={itemSurvey.type}
routes={routesObject}
removeHandler={this.removeCard}>
</Card>
);
}).bind(this) : '';