开发者问题收集

无法读取未定义的 React JS 的“handleClick”属性

2017-08-30
1122

我一直在尝试使用 React 的状态向带有类选项的 div 添加新类。请注意,我是 React 的初学者。

这是我的代码。handleClick() 在构造函数类之后声明。包含 bind(this) 以避免丢失 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;
1个回答

尝试一下:

{profilesCreatedBy.map((profileCreatedBy, index) => {
         return  <Col className="col-md-15">
                    <div onClick={this.handleClick} className={selectOption.join(" ")}>
                          {profileCreatedBy}
                    </div>
                 </Col>;
 })}

ES6 arrow function automatically preserves the current this context. For more explanation on context please have a look at this answer

Dev
2017-08-30