React.js:从子到父的 onClick 函数 [英] React.js: onClick function from child to parent

查看:20
本文介绍了React.js:从子到父的 onClick 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这篇文章为例(React方式),但它对我不起作用.请指出我的错误,因为我不明白出了什么问题.

这是我看到的错误:

<块引用>

未捕获的类型错误:this.props.onClick 不是函数

这是我的代码:

//父级var SendDocModal = React.createClass({获取初始状态:函数(){返回{标签列表:[]};},渲染:函数(){返回 (

{this.state.tagList.map(function(item) {返回 (<TagItem nameProp={item.Name} idProp={item.Id} onClick={this.HandleRemove}/>)})}</div>)},处理删除:函数(c){console.log('On REMOVE = ', c);}});//孩子var TagItem = React.createClass({渲染:函数(){返回 (<span className="react-tagsinput-tag"><span>{this.props.nameProp}</span><a className='react-tagsinput-remove' onClick={this.HandleRemove}></a></span>)},处理删除:函数(){this.props.onClick(this);}});

提前致谢!

解决方案

问题是 map 回调中的 this 没有引用 React 组件,因此 this.HandleRemoveundefined.

您可以通过将第二个参数传递给 map 来显式设置 this 值:

this.state.tagList.map(function() {...}, this);

现在this inside回调指的是与this相同的值outside回调,即SendDocModal 实例.

这与 React 无关,它只是 JavaScript 的工作方式.请参阅 如何访问正确的 `this` 上下文回调?了解更多信息和其他解决方案.

I used this article as an example (React way), but it is not working for me. Please point me to my mistake, as I can't understand what's wrong.

This is the error I see:

Uncaught TypeError: this.props.onClick is not a function

Here is my code:

// PARENT
var SendDocModal = React.createClass({
  getInitialState: function() {
    return {tagList: []};
  },
  render: function() {
    return (
      <div>
        {
          this.state.tagList.map(function(item) {
            return (
              <TagItem nameProp={item.Name} idProp={item.Id} onClick={this.HandleRemove}/>
            )
          })
        }
      </div>
    )
  },
  HandleRemove: function(c) {
    console.log('On REMOVE = ', c);
  }
});

// CHILD
var TagItem = React.createClass({
  render: function() {
    return (
      <span className="react-tagsinput-tag">
        <span>{this.props.nameProp}</span>
        <a className='react-tagsinput-remove' onClick={this.HandleRemove}></a>
      </span>
    )
  },
  HandleRemove: function() {
    this.props.onClick(this);
  }
});

Thanks in advance!

解决方案

The issue is that this inside the map callback does not refer to the React component, hence this.HandleRemove is undefined.

You can set the this value explicitly by passing a second argument to map:

this.state.tagList.map(function() {...}, this);

Now this inside the callback refers to the same value as this outside the callback, namely the SendDocModal instance.

This has nothing to do with React, it's just how JavaScript works. See How to access the correct `this` context inside a callback? for more info and other solutions.

这篇关于React.js:从子到父的 onClick 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆