【问题标题】:Why React can not find "this" in event handler [duplicate]为什么 React 在事件处理程序中找不到“this”[重复]
【发布时间】:2016-07-20 13:56:30
【问题描述】:

全部:

我对 React 很陌生,当我尝试制作一个非常简单的组件时,例如带有标签的输入框,标签可以根据输入框的输入而改变。

class App extends React.Component {
    constructor() {
        super();
        this.name = "World";
    }
    changeName(e){
        var nameinput = this.refs.nameinput;
        this.name = nameinput.value;
    }
    render(){
        return  (
            <div>
                <input ref="nameinput" onChange={this.changeName} />
                Hello, {this.name}!
            </div>
            );
    }
}

目前问题出在 changeName() 函数中,没有对 App 的引用(当我打印出 this 时,它是未定义的)我想知道如何使用 refs 之类的东西获得对该输入框的引用.nameinput.value

谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你需要绑定你的事件处理器:

    <input ref="nameinput" onChange={this.changeName.bind(this)}/>
    

    有关this的更多详细信息,请参阅此问题:

    How to access the correct `this` context inside a callback?

    【讨论】:

    • 谢谢,现在它可以工作了,但我想知道为什么渲染函数没有被调用,这是否意味着我每次运行事件 ahndler 时都必须手动调用 this.setState() ?我有点想知道我的状态数据结构是不是很深,如何在 setState() 中写(like this.AA.BB.CC.DD.XXX.name)?
    • 您需要致电setState。您需要将name 移动到组件的state 属性中。 setState 与现有状态进行浅层合并,但不会合并深度嵌套的对象(但是您可以使用 Object.assign 手动将嵌套数据与更改合并)。我建议您尝试扁平化您的数据并研究不变性。
    • 谢谢,好主意,我会读的
    【解决方案2】:

    或者你可以在你的构造函数中绑定它

    constructor() {
            super();
            this.name = "World";
            this.changeName = this.changeName.bind(this);
        }
    

    【讨论】:

    • 现在它可以工作了,但我想知道为什么渲染函数没有被调用,这是否意味着我每次运行事件 ahndler 时都必须手动调用 this.setState() ?我有点想知道我的状态数据结构是不是很深,在setState()中怎么写?
    猜你喜欢
    • 2015-11-28
    • 2015-06-17
    • 2015-06-26
    • 2016-12-28
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多