繁体   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