Uncaught TypeError: Cannot read property 'state' of undefined

后端 未结 3 2091
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 14:04

I am trying to change from React.createClass to React.Component, but I am getting below error.

Uncaught TypeError: Cannot read property \'state\' of undefined 
<         


        
3条回答
  •  难免孤独
    2021-01-29 14:39

    You need to bind this.onSelect If you forget to bind this.onSelect and pass it to onClick, this will be undefined when the function is actually called.

    Try this:

    class SectionAccordion extends React.Component {
    
          constructor(props){
            super(props);
            this.onSelect  = this.onSelect.bind(this);
          }
    
          onSelect() {
    
            this.props._onSelect(this.props.id);
          }
    
          render() {
    
                console.log("accordion / the Accordion Section component");
                var className = 'accordion-section' + (this.props._selected ? ' selected' : '');
    
                return (
                    

    {this.props.title}

    {this.props.children}
    ); } }

    Update:

    You can bind the context using arrow function as well ; like this:

    onSelect = () => {
       // code goes here
    }
    

提交回复
热议问题