最愚蠢的事情正在发生在我的代码上。我有一个在 DOM 中呈现的项目列表,我需要放置一个按钮才能调用另一个函数,如果我像这样放置按钮 <button></button>
一切正常,但如果我为该按钮分配一个功能,那么一切都会失败 <button onClick={function}></button>
我会告诉你我的代码,看
@connectToStores
export default class Dealers extends Component {
static contextTypes = {
router : React.PropTypes.func,
}
static propTypes = {
title : React.PropTypes.func,
}
constructor (props) {
super(props);
this.state = {
modal : false,
}
}
static getStores () {
return [ GetDealersStore ];
}
static getPropsFromStores () {
return GetDealersStore.getState();
}
render () {
let dealersInfo;
if (this.props.dealerData !== null) {
dealersInfo = this.props.dealerData.dealersData.map(function(dealer) {
return (<div key={dealer.DealerId} style={Styles.dealerCard}>
<Card>
<CardHeader title={dealer.NickName}
subtitle={dealer.DealerId}
avatar={dealer.Picture}/>
<CardText>
<FloatingActionButton> ////////////////////////
<IconAdd /> //////THIS IS THE BUTTON/////
</FloatingActionButton>//////////////////////
</CardText>
</Card>
</div>
);
});
} else {
dealersInfo = <p>Loading . . .</p>;
}
return (
<Grid>
<Row>
<Column><h4>Dealers</h4></Column>
</Row>
<div style={Styles.mainCont}>
{dealersInfo}
</div>
</Grid>
);
}
componentWillMount () {
GetDealersActions.getDealers();
}
_openUpdateDealer = () => {
console.log(123);
}
}
如你所见,有一个声明
if (this.props.dealerData !== null) {
...
}else {
dealersInfo = <p>Loading . . .</p>;
}
当我将代码粘贴到上面时,一切都很棒,但是如果我添加 <FloatingActionButton onClick={this._openUpdateDealer.bind(this)}><IconAdd /></FloatingActionButton>
然后一切都崩溃了,我在屏幕上看到的是Loading . . .
这是 else
在上面的声明中。
所以,我想知道,这里的 React 是怎么回事?
最佳答案
您在 .map
操作的中间呈现按钮:
this.props.dealerData.dealersData.map(function(dealer) {
它为 this
使用不同的值;因此,函数内部不存在 this.props
。我希望在浏览器控制台中看到 cannot read property dealerData of undefined
。
您需要使用 the optional thisArg
parameter :
this.props.dealerData.dealersData.map(function(dealer) {
// ...
}, this);
bind the mapping function to this
手动:
this.props.dealerData.dealersData.map(function(dealer) {
// ...
}.bind(this));
或使用 an arrow function (因为您使用的是 ES6 功能):
this.props.dealerData.dealersData.map((dealer) => {
// ...
});
关于javascript - 如果我在 `onClick` 中引用 `map` 中的方法,为什么我的组件会损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028315/