this 的值未定义 [英] Value of this is undefined

查看:38
本文介绍了this 的值未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 if 语句中有一个 this 值,嵌套在我的 handleFormChange 函数中.我尝试使用带有此函数的箭头函数来绑定 this 的值,但我收到以下错误消息:

TypeError: 无法设置未定义的属性作者"

根据我的理解,通常您可以通过查看包含 this 的函数的调用位置来找到 this 值.但是,就我而言,我正在努力解决这个问题.谁能向我解释为什么它是未定义的以及如何解决这个问题?代码如下:

class CommentForm extends React.Component{构造函数(道具){超级(道具)var 评论={作者:'',消息:''}}handleSubmit= (e)=>{e.preventDefault()var authorVal = this.comment.author;var textVal = this.comment.message;//如果有任何遗漏,这将停止任何评论提交如果 (!textVal || !authorVal) {返回;}this.props.onCommentSubmit(this.comment);//重置表单值e.target[0].value = '';e.target[1].value = '';返回;}handleFormChange= (e)=>{e.preventDefault()if(e.target.name==='作者'){var author = e.target.value.trim();this.comment.author = 作者}else if(e.target.name==='message'){var message = e.target.value.trim();this.comment.message = 消息}}使成为() {返回 (<form className = "ui form" method="post" onChange={(e)=>{this.handleFormChange(e)}} onSubmit={(e)=>{this.handleSubmit(e)}}><div className="form-group"><输入className="表单控件"占位符=用户..."姓名=作者"类型=文本"/>

<div className="form-group"><文本区域类名=表单控件"占位符=评论..."名称=消息"/>

<div className="form-group"><button disabled={null} className="btn btn-primary">评论 &#10148;

</表单>);}}导出默认评论表单

解决方案

学习如何做你想做的事的第一步是研究 React 的 State 是如何工作的 (官方文档 非常善于解释.

这个例子并不完整,但应该会引导你完成整个过程.

class CommentForm extends Component {构造函数(道具){超级(道具);this.state = {作者  : '',信息 : '',}this.onChangeAuthorName = this.onChangeAuthorName.bind(this);this.onBlurAuthorName = this.onBlurAuthorName.bind(this);}onChangeAuthorName(e) {this.setState({作者: e.target.value });}onBlurAuthorName() {//修剪模糊(或当您发送到网络时,以避免//让用户无法添加空的空格//打字时this.setState({ 作者: this.state.author.trim() })}使成为() {返回 (...<输入值={this.state.author} onChange={this.onChangeAuthorName} onBlur={this.onBlurAuthorName}/>...);}}

通常,当您想在 React 中设置"变量时,您不会像在 Javascript 类中那样添加它们(this.comment = e.target.value),而是, 使用函数 setState().来自文档:

//错误this.state.comment = '你好';相反,使用 setState()://正确的this.setState({comment: '你好'});

(注意:或者,这可以使用 React Hooks 来完成,但我建议您直接学习生命周期方法.祝你好运!)

I have a this value inside an if statement, nested inside a my handleFormChange function. I've tried to use arrow functions with this function to bind the value of this but im getting the following error message:

TypeError: Cannot set property 'author' of undefined

From my understanding usually you find the this value by looking at where the function containing this is called. However, in my case im struggling to work this out. Can anyone explain to me why it is undefined and how to solve this issue? Here is the code:

class CommentForm extends React.Component{

    constructor(props){
        super(props)


        var comment={author:'', message:''}
    }


    handleSubmit= (e)=>{
        e.preventDefault()
        var authorVal = this.comment.author;
        var textVal = this.comment.message;
        //this stops any comment submittal if anything missing
        if (!textVal || !authorVal) {
         return;
        }
        this.props.onCommentSubmit(this.comment);
        //reset form values
        e.target[0].value = '';
        e.target[1].value = '';
        return;
    }


    handleFormChange= (e)=>{
        e.preventDefault()
        if(e.target.name==='author'){
            var author = e.target.value.trim();
            this.comment.author = author
        }else if(e.target.name==='message'){
            var message = e.target.value.trim();
            this.comment.message = message
        }
    }

    render() {
    return (

        <form className = "ui form" method="post" onChange={(e)=>{this.handleFormChange(e)}} onSubmit={(e)=>{this.handleSubmit(e)}}>
          <div className="form-group">
            <input
              className="form-control"
              placeholder="user..."
              name="author"
              type="text"
            />
          </div>

          <div className="form-group">
            <textarea
              className="form-control"
              placeholder="comment..."
              name="message"        
            />
          </div>



          <div className="form-group">
            <button disabled={null} className="btn btn-primary">
              Comment &#10148;
            </button>
          </div>
        </form>

    );
  }
}

export default CommentForm

解决方案

The first step into learning how to do what you want is to study how React's State works (official docs are great at explaning it).

This example is not complete, but should guide you through the proccess.

class CommentForm extends Component {

constructor(props) {
  super(props);

  this.state = {
    author  : '',
    message : '',
  }

  this.onChangeAuthorName = this.onChangeAuthorName.bind(this);
  this.onBlurAuthorName   = this.onBlurAuthorName.bind(this);
}

onChangeAuthorName(e) {
  this.setState({ author: e.target.value });
}

onBlurAuthorName() {
  // trim on blur (or when you send to the network, to avoid
  // having the user not being able to add empty whitespaces
  // while typing
  this.setState({ author: this.state.author.trim() })
}

render() {
  return (
    ...
    <input value={this.state.author} onChange={this.onChangeAuthorName} onBlur={this.onBlurAuthorName} />
    ...
  );
}

}

Usually, when you want to "set" variables in React, you don't add them as you do to in Javascript classes (this.comment = e.target.value), but instead, use the function setState(). From the docs:

// Wrong
this.state.comment = 'Hello';

Instead, use setState():

// Correct
this.setState({comment: 'Hello'});

(NOTE: Alternatively, this could be done using React Hooks, but I recommend you learn the lifecycle methods firsthand. Good luck!)

这篇关于this 的值未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆