`bind`不适用于ReactJS中的导入函数

时间:2018-10-19 17:37:08

标签: javascript reactjs bind

我的视图看起来像这样(但为简单起见,我将其缩小了)

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;
    }
}

核心问题

  • 我需要做些什么才能使用bind访问validate.js内部的this.state.validation? (我想避免通过this来验证为参数)

需要理解的问题

  • 为什么控制台在validate.js中输出undefined,但是如果我在调试器中输出变量,则会得到期望的值?

2 个答案:

答案 0 :(得分:0)

就像skyboyer一样,问题在于绑定箭头功能

validate.js中的内容已更改

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

export const Validate = function ({ currentTarget }) {

答案 1 :(得分:-1)

您可以改用this.validate = Validate.bind(this);吗?