【问题标题】:Cant pass class method to an onClick from within its render method in ReactJS? [duplicate]不能在 ReactJS 的渲染方法中将类方法传递给 onClick? [复制]
【发布时间】:2018-07-27 05:25:59
【问题描述】:

如果这听起来像是一个新问题,我很抱歉。还没找到答案。

我基本上是在尝试使用一个类的方法作为我 JSX 中 onClick 的回调。

这是我的 App 组件的代码:

import React from 'react';
import PropTypes from 'prop-types';

class App extends React.Component {
  constructor(props) {
      super(props);
      this.deletePost = this.deletePost.bind(this);
  }

  deletePost() {
    //   this.props.posts = this.props.posts.splice(i,1)
    console.log("Deleted the post");
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to learn React</h1>
        </header>

        <div>
            <input type="text"/>
            <button>Post</button>
        </div>

        <br/>

        <div className="post-list">
            <hr/>
            {this.props.posts.map(function(post, i){
               return <div>
                    {post} - {i}
                    <button onClick={this.deletePost}>Del</button>
                    <hr/>
                </div>;
            })}
        </div>

      </div>
    );
  }
}

App.propTypes = {
  posts: PropTypes.array
};

export default App;

我得到的错误如下:

TypeError: Cannot read property 'deletePost' of undefined
(anonymous function)
src/components/App.js:34
  31 | {this.props.posts.map(function(post, i){
  32 |    return <div>
  33 |         {post} - {i}
> 34 |         <button onClick={this.deletePost}>Del</button>
  35 |         <hr/>
  36 |     </div>;
  37 | })}

所以我的问题是如何将 deletePost 函数传递给 onClick?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    问题是 this 在映射函数回调中未定义。你能用arrow functions吗?你有必要的转译吗?如果是,使用箭头函数可以解决这个问题:

    {this.props.posts.map((post, i) => { // <-- arrow function
        return <div>
            {post} - {i}
            <button onClick={this.deletePost}>Del</button>
            <hr/>
        </div>;
    })}
    

    如果你不能或不想在那里使用箭头功能,你可以这样做:

    render() {
    const deletePost = this.deletePost; // Save variable while we have access to this
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to learn React</h1>
        </header>
    
        <div>
            <input type="text"/>
            <button>Post</button>
        </div>
    
        <br/>
    
        <div className="post-list">
            <hr/>
            {this.props.posts.map(function(post, i){
               return <div>
                    {post} - {i}
                    <button onClick={deletePost}>Del</button>
                    <hr/>
                </div>;
            })}
        </div>
    
      </div>
    );
    

    }

    【讨论】:

    • 或者可以在传递给map的匿名函数上使用.bind(this)this.props.posts.map(function (...) {...}.bind(this))
    • 上面的答案和评论都有帮助。非常感谢@Gleb Kost 和 ArneHugo
    【解决方案2】:

    TypeError:无法读取未定义的属性“deletePost”?

    它与this 绑定的问题。使用arrow function 来解决问题。

     {this.props.posts.map((post, i)=>{
                       return <div>
                            {post} - {i}
                            <button onClick={this.deletePost}>Del</button>
                            <hr/>
                        </div>;
                    })}
    

    【讨论】:

      【解决方案3】:

      对于this 的预期值,使用 ES6 箭头函数:

      {this.props.posts.map((post, i) => {
        return (
          <div>
            {post} - {i}
            <button onClick={this.deletePost}>Del</button>
            <hr/>
          </div>
         );
       }}
      

      【讨论】:

        【解决方案4】:

        尝试箭头函数(Es6 功能):

             constructor(props) {
                 super(props);
              }
        
              deletePost = () => {
                   console.log("Deleted the post");
               }
        
         inside map function also use arrow
        
           {this.props.posts.map((post, i) => {
                   return <div>
                        {post} - {i}
                        <button onClick={this.deletePost}>Del</button>
                        <hr/>
                    </div>;
                })}
        

        必须更改:babel 预设 es2015 --> es2016 并添加 stage-2

        ex:
           Webpack.js
        
         module: {
           loaders: [
              {
                 test: /\.jsx?$/,
                 exclude: /node_modules/,
                 loader: 'babel-loader',
                 query: {
                    presets: ['es2016', 'react', 'stage-2'] //Add ES6 features 
                 }
              }
           ]
        }
        

        【讨论】:

        • 这仍然会抛出同样的错误
        • 检查 webpack 配置
        • 好的,对地图回调的最后一次编辑,它会工作
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 2020-04-06
        • 2018-07-06
        • 2012-03-15
        • 2016-11-01
        • 2015-06-30
        相关资源
        最近更新 更多