我一直在尝试使用React状态向class选项添加一个新类。要注意,我是React的初学者。
这是我的代码。在构造函数类之后声明handleClick()。包含bind(this)以免松散到何处。我想理解为什么我仍然会收到类型错误,并将消息“handleClick”定义为未定义。
import React, { Component } from 'react';
import {Grid, Col, Row, Button} from 'react-bootstrap';
import facebook_login_img from '../../assets/common/facebook-social-login.png';
const profilesCreatedBy = ['Self' , 'Parents' , 'Siblings' , 'Relative' , 'Friend'];
class Register extends Component {
constructor(props) {
super(props);
this.state = { addClass: false };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ addClass: !this.state.addClass });
}
render() {
let selectOption = ["option"];
if (this.state.addClass) {
selectOption.push("option-active");
}
return (
<section className="get-data__block" style={{padding: '80px 0 24px 0'}}>
<Grid>
<Row>
<Col sm={10} md={8} mdOffset={2} smOffset={1}>
<p className="grey-text small-text m-b-32"><i>
STEP 1 OF 6 </i>
</p>
<div className="data__block">
<div className="step-1">
<p className="m-b-32">This profile is being created by</p>
<Row>
{profilesCreatedBy.map(function(profileCreatedBy, index){
return <Col className="col-md-15">
<div onClick={this.handleClick} className={selectOption.join(" ")}>
{profileCreatedBy}
</div>
</Col>;
})}
</Row>
</div>
</div>
</Col>
</Row>
</Grid>
</section>
);
}
}
export default Register;
答案 0 :(得分:3)
试试这个:
{profilesCreatedBy.map((profileCreatedBy, index) => {
return <Col className="col-md-15">
<div onClick={this.handleClick} className={selectOption.join(" ")}>
{profileCreatedBy}
</div>
</Col>;
})}
ES6 arrow function会自动保留当前的上下文。 有关上下文的更多说明,请查看此answer