反应onclick侦听器

时间:2019-05-08 17:40:55

标签: reactjs

因此,我创建并遵循了一些教程,但仍然无法使onClick侦听器正常工作。有人可以建议吗?

我尝试实现给定的示例(基于我的代码(类似)),并且未调用onClick函数。我也尝试过onClick = {function(e){console.log('clicked')}},但控制台未响应

import React, {Component} from 'react';
import './App.css';

class App extends Component {
  ClearNewNote = (e) => {
    e.target.style.backgroundColor = '#ccc';
  };
  render() {
    return(
      <div className="App">
        <header className="App-header">
          <h1>Simple Note Pad</h1>
        </header>
        <main>
          <div className="CreateNewNote">
            <div className="Controls">
              <button className="ClearNewNote">Clear</button>
              <button className="SaveNewNote" onClick={this.ClearNewNote.bind(this)}>Save</button>
            </div>
            <div className="NewNoteInput">
              <textarea></textarea>
            </div>
          </div>
        </main>
      </div>
    );
  };
}

export default App;

编辑:更新为符合建议,单击时没有错误代码,也没有更改

2 个答案:

答案 0 :(得分:1)

选中这个

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  ClearNewNote(e) {
    e.currentTarget.style.backgroundColor = "red";
  }

  render() {
    return (
      <div>
        <button onClick={this.ClearNewNote}>Click on me</button>
      </div>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

答案 1 :(得分:1)

使用箭头函数在this中使用Component上下文。并将currentTarget更改为target

  ClearNewNote = (e) => {
    e.target.style.backgroundColor = '#ccc';
  };