javascript - 该值未定义

标签 javascript reactjs this

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

TypeError: Cannot set property 'author' of undefined

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

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

最佳答案

学习如何做你想做的事情的第一步是研究 React 的 State 是如何工作的(official docs 非常擅长解释它)。

此示例并不完整,但应该可以指导您完成整个过程。

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} />
    ...
  );
}

}

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

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

Instead, use setState():

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

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

关于javascript - 该值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034553/

相关文章:

javascript - 从回调函数中获取值

javascript - Angularjs 自定义过滤器和依赖注入(inject)

javascript - meteor 更新图表

javascript - Chart.js 不会显示正常图表

javascript - 函数作为 React 子项无效。 - React 中的功能组件

c# - 在 C# 中使用带有类名的 “this”

ReactJS + 样式组件 + 伪类

javascript - 两个组件可以在reactjs中显示

JavaScript this 关键字惊喜

javascript - 传递给 __defineGetter__ 的函数中 "this"的值是多少