代码之家  ›  专栏  ›  技术社区  ›  Nikul Panchal

react js onclick函数不调用

  •  1
  • Nikul Panchal  · 技术社区  · 7 年前

    我是React JS的新手,我想点击一下,但当我点击按钮时,它会说 this is undefined ,有人能帮我解决这个错误吗?我已经发出警报,检查是否 deleteTask 是否有效,但该函数不调用,这是我的完整代码

    class PalladiumHub extends React.Component {
      render() {
    
        return (<tr>
          <td>{this.props.name.id}</td>
          <td>{this.props.name.name}</td>
          <td><button type="button">Edit</button><button onClick={function(e) { this.props.deleteTask(this.props.key) } }>Delete</button></td> 
          </tr>
        )
      }
    } //{} {}
    
    class CallCRUD extends React.Component {
    
      constructor(props) {
        super(props);
        this.deleteTask = this.deleteTask.bind(this);
        this.state = {
          error: null,
          isLoaded: false,
          items: []
        };
      }
    
      componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then(res => res.json())
          .then(
            (result) => {
    
              this.setState({
                isLoaded: true,
                items: result
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }
    
    
      deleteTask(index) {   
          alert('sdsd');
          console.log(index);
          //return false;
          let tasks = this.state.items;
    
          tasks.splice(index,1);
          this.setState({
              items:tasks
          })
      }
    
      render() {
        console.log(this.state.items);
        return (<table border="1"> <tr><th>ID</th><th>Name</th><th>Action</th></tr> {
          this.state.items.map( (data,index) => {
            return <PalladiumHub name={data} key={data.id} deleteTask ={this.deleteTask} />
          })
    
        }
          </table>
          );
        }
    
    
      }
      ReactDOM.render(
      <CallCRUD />, document.getElementById('root')
    );
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Just code    7 年前

    不使用函数,它们会删除 this 绑定

    onClick={function(e) { this.props.deleteTask(this.props.key) } }
    

    把它改成

    onClick={(e) => this.props.deleteTask(this.props.key)}
    

    另外,我想让你读一下 this

        2
  •  1
  •   Charles Chazz Sohier    7 年前

    您好,您需要绑定onclick处理程序。 签出此页 https://reactjs.org/docs/handling-events.html

    class PalladiumHub extends React.Component {
    
    onClick = () => {
     this.props.deleteTask(this.props.key)
    }
    render() {
      return (<tr>
      <td>{this.props.name.id}</td>
      <td>{this.props.name.name}</td>
      <td><button type="button">Edit</button><button onClick={this.onClick.bind(this)}>Delete</button></td> 
      </tr>)
     }
    }