【问题标题】:Class Syntax : React Component Fires the OnChange within Closure类语法:React 组件在闭包中触发 OnChange
【发布时间】:2017-10-04 07:10:18
【问题描述】:

在我的React 代码中,要创建一个闭包,我调用“onChange”

class CityInput extends React.Component {
    constructor( props ){
        super( props );
        this.state = {
            city : "",
            country : ""
        };
        this.setChangeType = this.setChangeType( this );
        this.onChange = this.onChange.bind( this );
    }

    setChangeType( cityOrCountry ){
        return this.onChange;
    }

    onChange( e ){
        console.log( "e.target.value", e.target.value );
        this.setState({
            [ cityOrCountry ] : e.target.value
        })
    }
    ...
    render(){
        return(
            <form onSubmit = { this.onEnter }>
                <label>
                    City : 
                    <input type = "text"
                             name = "cityName"
                             placeholder = "london"
                             value = { this.state.city }
        // the following line executes 'setChangeType' on render,
        // which is suppose to return 'onChange' func, ready to be
        // executed once the onChange is fired by the user.
        // However, thats not happening right now, the function
        // 'onChange' is also fired by 'setChangeType' & I 
        // get the error : 'e.target is undefined'
                             onChange = { this.setChangeType( "city" )} />
                </label>
             .... // rest of form
            </form>
        );
    }
};

出于某种原因,我不明白,函数 'this.setChangeType("city")' 被正确触发,但是,onChange 也被触发,而不是返回函数 'onChange'。我做错了什么?

我收到控制台错误:“e.target is undefined”

【问题讨论】:

    标签: javascript class reactjs closures


    【解决方案1】:

    问题是

    this.setChangeType = this.setChangeType( this );
    

    应该是

    this.setChangeType = this.setChangeType.bind( this );
    

    但是,您也可以完全删除该行,因为您的代码不需要正常工作(您没有使用 setChangeType 作为回调)。

    否则,this.setChangeType 将具有与this.onChange 相同的值,即调用this.setChangeType('city') 实际上调用this.onChange('city')

    【讨论】:

    • 你知道为什么'onChange'函数不能访问变量'cityOrCountry'吗?我会认为我创建了一个闭包,这就是“setChangeType”函数的全部意义所在。
    • 您只能通过在定义变量的范围内定义函数来创建闭包。 return this onChange 没有定义函数,它返回对现有函数的引用。你可以改用return e =&gt; this.onChange(e, cityOrCountry);,但是你也可以在render方法中内联它:onChange = { e =&gt; this.onChange(e, "city" )}。然而,每次渲染组件时,两者都会创建一个新函数,这可能会导致输入出现奇怪的行为。
    • 您最好创建一个新组件,将cityOrCountry 作为道具并呈现输入。
    • 两者都有好处。非常感谢。关于闭包的那一行非常有意义,是的,我应该为输入创建一个新组件。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2019-09-29
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多