簡體   English   中英

我的構造函數無法訪問

[英]my functions in constructor are not reachable

我是Reactjs和jsx的新手。 我需要在我的React項目中使用html5的onDragOver和onDragStart功能。 因此,我在mycode的構造函數中定義了以下函數:

 export class Navbar extends React.Component {

constructor(props) {
    super();
    var allowDrop = function allowDrop(ev) {
        ev.preventDefault();
    }

    function drag(ev) {
        ev.dataTransfer.setData("source", ev.target.id);
    }

    function drop(ev) {
        ev.preventDefault();
        var src = document.getElementById(ev.dataTransfer.getData("source"));
        var srcParent = src.parentNode;
        var tgt = ev.currentTarget.firstElementChild;

        ev.currentTarget.replaceChild(src, tgt);
        srcParent.appendChild(tgt);
    }

}

componentDidMount() {
  }

render() {
    return (
        <ul className="navigation">
            <li id="t1" className="nav-item" onDrop={this.drop(event)} onDragOver={this.allowDrop(event)}><a href="#"
                                                                                                        draggable="true"
                                                                                                        onDragStart={thisdrag(event)}>Greater
                Saint John</a></li>


            <li className="nav-item" id="t2" ondrop={this.drop(event)} onDragOver={this.allowDrop(event)}><a href="#"
                                                                                                        draggable="true"
                                                                                                        onDragStart={this.drag(event)}><span
                className="glyphicon glyphicon-star"></span>&nbsp;&nbsp;    The Victoria Star</a></li>

        </ul>
     );
   }
   }

但是當我運行它時,出現以下錯誤:

Uncaught TypeError: this.allowDrop is not a function

有人可以幫忙嗎?

這是因為allowDrop是一個函數表達式,因此在構造函數外部不可見。

function allowDrop(ev) { ev.preventDefault(); }

如上所述聲明allowDrop,這應該可以解決問題。 有關函數聲明與函數表達式的更多詳細信息: https : //javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM