React.js - REF undefined

React.js - REF undefined

本文关键字:undefined REF js React      更新时间:2024-06-27

当我测试以下代码时,我收到一个控制台错误,newText未定义,我是正确地声明了val var,还是遗漏了什么?

val = ReactDOM.findDOMNode(this.refs[newText]);
renderForm: function() {
        return (
            <div className="note">
                <textarea ref="newText" defaultValue={this.props.children} className="form-control"></textarea>
                <button onClick={this.save} className="btn btn-success btn-sm glyphicon glyphicon-floppy-disk"></button>
            </div>
        )
    },

newText这里需要是字符串("newText"),或者应该使用点表示法。仅使用newText意味着您正在尝试读取具有该名称的变量的值(它将返回undefined)。

更改:

this.refs[newText]

收件人:

this.refs["newText"]

或者:

this.refs.newText

我知道现在回答这个问题已经很晚了,但我遇到了同样的问题。

我添加并更新了以下来源:src="https://unpkg.com/react@15/dist/areact.js">src="https://unpkg.com/react-dom@15/dist/rect dom.js">

它对我有效。

希望你已经找到了解决方案。干杯

使用this.refs.newText而不是this.refs[newText]