簡體   English   中英

這在反應輸入onChange中丟失

[英]this is missing, in react input onChange

在onChange函數中我沒有這個,所以沒有道具,也沒有狀態我在做什么錯? 謝謝

編輯:添加了類和構造函數!

export default class Editor extends Component {
constructor(props) {
    super(props);
    this.state = {
      sortDirection: true,
      json: props.json, // using a prop called json. were setting state.data to json
      options: props.options || {}, //optional object options
      id:props.id,
    }
  }
 onChange = (e) => {
    let xyz=this
    /// this is undefined. needed to set state on controlled input
   }


buildKeys = () => {
    let keys = Object.keys(this.state.json[0]);
    let self = this
    return keys.map((key, index) => {
      // hide column if columname in hidden columns array
      /// if no hidecol option we set it an empty array
      let hiddenColArr = self.state.options.hideCol || []
      // loops throgh hiddenCol array and returns a bool
      let isHidden =  _.includes(hiddenColArr, key) 

     // build values
     let arrIndex=this.props.id -1
     let row = this.state.json[arrIndex];

     return Object.keys(row).map((key2)  =>

     <div key={shortid.generate()} className='row'   >{key}
    ////////////////*Input added here/
        <input  onChange={this.onChange} key={shortid.generate()} type="text" value={row[key2]} />
    /////////////////Input end here/

     </div>

     )

}

當使用類符號(React 16中的唯一選擇)時,您需要使用箭頭函數,即<Thing onChange={() => this.onChange()} .../> 為了保存this

如果您不這樣做,那么在onChange觸發時,該調用的執行上下文將保證不是您的組件,並且很可能只是window

您還需要將那些實例屬性更改為普通的類函數:

class Thing extends Component {
  constructor(props) {
    super(props);
    this.state = ...
  }

  onChange(evt) {
    // do what needs to be done
  }

  render() {
    return <div ... >
      <input onChange={evt => this.onChange(evt)} ... />
    </div>;
  }
}

實際上,如果您使用的是Babel + Webpack,我幾乎可以保證您已經是Babel對您的代碼所做的事情,因此運行的代碼將具有普通的類函數,因此您確實需要使用箭頭函數作為onChange處理程序。

(一些教程主張將this.onChange = this.onChange.bind(this)放入構造函數中,我不建議您這樣做。知道其余類的樣子不是構造函數的工作)

您可以綁定this在你的構造函數綁定到您的功能:

...
constructor(props){
    super(props);
    this.onChange = this.onchange.bind(this);
}
...

暫無
暫無

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

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