简体   繁体   中英

`bind` not working for imported function in ReactJS

My view looks something like this (but I've slimmed it down for simplicity)

view.jsx

import * as R from 'ramda';
import { Validate } from 'src/utils/validate';

class example extends Component {
    constructor(props) {
        super(props);

        this.state = {
            model: EMPTY_MODEL,
            validation: EMPTY_VALIDATION,
        };
        this.validate = R.bind(Validate, this);
    }

    render() {
        <div>
            <input
                id="example"
                type="text"
                onChange={ this.validate }
            />
        </div>
    }
}

validate.js

import * as R from 'ramda';

export const Validate = ({ currentTarget }) => {
    console.log(this); // outputs: {}
    console.log(this.state); //outputs: undefined
    debugger; //console.log(this.state); outputs { model: {}, validation: {} }

    let { validation } = this.state; //Error: Cannot read prop 'validation'of undefined
    const { id, value } = currentTarget;

    switch (currentTarget.id) {
        case 'example':
            if(value.length < 4) {
                this.setState({
                    validation: R.assocPath([id, 'valid'], false, validation),
                });
            }
            break;
        default:
            break;
    }
}

Core Question

  • What do I need to do to have access to this.state.validation inside of validate.js using bind? (I would like to avoid passing this to validate as a param)

Questions to understand

  • Why does console output undefined in validate.js, but if I output variables during the debugger I get the expected values?

As skyboyer eluded to, the issues is binding a arrow function

In validate.js changed

export const Validate = ({ currentTarget }) => {

to

export const Validate = function ({ currentTarget }) {

Can you try this.validate = Validate.bind(this); instead?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM