代码之家  ›  专栏  ›  技术社区  ›  Seth McClaine

` bind`not working for imported函数in reactjs

  •  0
  • Seth McClaine  · 技术社区  · 6 年前

    我的观点看起来像这样(但为了简单起见,我把它简化了)

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

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

    核心问题

    • 我需要做什么才能接触到 this.state.validation 在validate.js中使用bind?(我想避免路过 this 作为参数进行验证)

    需要理解的问题

    • 为什么控制台输出 undefined 在validate.js中,但是如果我在调试器期间输出变量,我会得到预期的值吗?
    2 回复  |  直到 6 年前
        1
  •  0
  •   Seth McClaine    6 年前

    AS skyboyer 回避的是,问题是绑定一个箭头函数

    在validate.js中更改

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

    export const Validate = function ({ currentTarget }) {
    
        2
  •  -1
  •   Praveeta Singh    6 年前

    你能试试吗? this.validate = Validate.bind(this); 相反?