Uncaught TypeError: Cannot read property 'state or props' of undefined

前端 未结 2 1456
[愿得一人]
[愿得一人] 2020-11-22 04:29

So I started converting my application from ES2015 to ES6 which uses React.

I have a parent class and a child class like so,

export default class Par         


        
2条回答
  •  Happy的楠姐
    2020-11-22 04:45

    You can use arrow function to bind you functions. You need to bind you functions both in child as well as parent components.

    Parent:

    export default class Parent extends Component {
        constructor(props) {
            super(props);
            this.state = {
                code: ''
            };
        }
    
        setCodeChange = (newCode) => {
            this.setState({code: newCode});
        }
    
    
        login = () => {
            if (this.state.code == "") {
                // Some functionality
            }
        }
    
        render() {
            return (
                
    ); } }

    Child

    export default class Child extends Component {
        constructor(props) {
            super(props);
        }
    
        handleCodeChange = (e) => {
            this.props.onCodeChange(e.target.value);
        }
    
        login = () => {
            this.props.onLogin();
        }
    
        render() {
            return (
                

    There are other ways to bind the functions as well such as the one you are using but you need to do that for parent component too as

    or you can specify binding in the constructor as

    Parent:

    constructor(props) {
        super(props);
        this.state = {
            code: ''
        };
     this.setCodeChange = this.setCodeChange.bind(this);
     this.login = this.login.bind(this);
    }
    

    Child

    constructor(props) {
        super(props);
        this.handleCodeChange = this.handleCodeChange.bind(this);
        this.login = this.login.bind(this);
    }
    

提交回复
热议问题