美文网首页
TypeError: Cannot read property

TypeError: Cannot read property

作者: w晚风 | 来源:发表于2021-04-10 23:47 被阅读0次

    问题描述:

    react组件中的方法获取state中的值时报错:TypeError: Cannot read property ‘state’ of undefined

    解决办法:

    方法一(在constructor中绑定this到函数):this.funOne = this.funOne.bind(this);

    import React , {Component} from 'react'; 
    
    class Home extends Component {
        constructor(props){
            super(props); 
    
            this.state = {
                one: 'one'
            }
    
            this.funOne = this.funOne.bind(this); // 主要是这一行绑定this到函数funOne
        }
    
        funOne () {
            alert(this.state.one)
        }
        
        render () {
            return (
                <div className="Home">
                    <button onClick={this.funOne}>funOne</button>
                </div>
            );
        }
    }
    
    export default Home;
    
    

    方法二(使用箭头函数):funOne = () => {}

    import React , {Component} from 'react'; 
    
    class Home extends Component {
        constructor(props){
            super(props); 
    
            this.state = {
                one: 'one'
            }
        }
    
        funOne = () => {
            alert(this.state.one)
        }
        
        render () {
            return (
                <div className="Home">
                    <button onClick={this.funOne}>funOne</button>
                </div>
            );
        }
    }
    
    export default Home;
    
    

    方法三(绑定方法的同时绑定this):onClick={this.funOne.bind(this)}

    import React , {Component} from 'react'; 
    
    class Home extends Component {
        constructor(props){
            super(props); 
    
            this.state = {
                one: 'one'
            }
        }
    
        funOne () {
            alert(this.state.one)
        }
        
        render () {
            return (
                <div className="Home">
                    <button onClick={this.funOne.bind(this)}>funOne</button>
                </div>
            );
        }
    }
    
    export default Home;
    
    

    相关文章

      网友评论

          本文标题:TypeError: Cannot read property

          本文链接:https://www.haomeiwen.com/subject/bimokltx.html