react:onClick 按钮不起作用

IT技术 javascript node.js reactjs
2021-04-29 12:31:28

在过去的一个小时里,我一直在努力让它发挥作用。onClick 上的任何按钮根本不起作用......我做错了什么?

const React = require('react');

class Questionnaire extends React.Component {
constructor (props) {
    super(props);
    this.state = { selectedSection: 0 };
}

selectSection (e) {
    console.log(e);
}

render () {
    return (
        <div>
            <div className='btn-group mr-2' role='group'>
                <button className='btn btn-primary' onClick={this.selectSection}>A</button>
                <button className='btn btn-secondary' onClick={this.selectSection}>B</button>
                <button className='btn btn-secondary' onClick={this.selectSection}>C</button>
                <button className='btn btn-secondary' onClick={this.selectSection}>D</button>
          </div>
        </div>
    );
}
}

 module.exports = Questionnaire;

我应该提到我将它与 express-react-views 一起使用

3个回答

您需要将函数绑定到组件,如下所示:

class Questionnaire extends React.Component {
    constructor (props) {
        super(props);
        this.state = { selectedSection: 0 };

        this.selectSection = this.selectSection.bind(this)
    }

保持其他一切不变

试试这个

    const React = require('react');

    class Questionnaire extends React.Component {
    constructor (props) {
        super(props);
        this.state = { selectedSection: 0 };
    }

    selectSection = function(e){
    console.log(e);
  }

    render () {
        return (
            <div>
                <div className='btn-group mr-2' role='group'>
                    <button className='btn btn-primary' onClick={this.selectSection}>A</button>
                    <button className='btn btn-secondary' onClick={this.selectSection}>B</button>
                    <button className='btn btn-secondary' onClick={this.selectSection}>C</button>
                    <button className='btn btn-secondary' onClick={this.selectSection}>D</button>
              </div>
            </div>
        );
    }
    }

您需要将方法绑定到类。将此行添加到构造函数:

this.selectSection = this.selectSection.bind(this);