React JS onClick event handler

前端 未结 11 1086
孤街浪徒
孤街浪徒 2020-11-28 21:35

I have

var TestApp = React.createClass({
      getComponent: function(){
          console.log(this.props);
      },
      render: function(){
        retur         


        
相关标签:
11条回答
  • 2020-11-28 21:59

    Use ECMA2015. Arrow functions make "this" a lot more intuitive.

    import React from 'react';
    
    
    class TestApp extends React.Component {
       getComponent(e, index) {
           $(e.target).css({
               'background-color': '#ccc'
           });
       }
       render() {
           return (
               <div>
                 <ul>
                   <li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
                   <li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
                   <li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
                 </ul>
               </div>
           );
       }
    });
    React.renderComponent(<TestApp /> , document.getElementById('soln1'));`
    
    0 讨论(0)
  • 2020-11-28 21:59

    import React from 'react';
    
    class MyComponent extends React.Component {
    
      getComponent(event) {
          event.target.style.backgroundColor = '#ccc';
          
          // or you can write
          //arguments[0].target.style.backgroundColor = '#ccc';
      }
    
      render() {
        return(
           <div>
             <ul>
                <li onClick={this.getComponent.bind(this)}>Component 1</li>
             </ul>
           </div>
        );
      }
    }
    
    export { MyComponent };  // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'
    export default MyComponent;

    0 讨论(0)
  • 2020-11-28 21:59

    This is a non-standard (but not so uncommon) React pattern that doesn't use JSX, instead putting everything inline. Also, it's Coffeescript.

    The 'React-way' to do this would be with the component's own state:

    (c = console.log.bind console)

    mock_items: [
        {
            name: 'item_a'
            uid: shortid()
        }
        {
            name: 'item_b'
            uid: shortid()
        }
        {
            name: 'item_c'
            uid: shortid()
        }
    ]
    getInitialState: ->
        lighted_item: null
    render: ->
        div null,
            ul null,
                for item, idx in @mock_items
                    uid = item.uid
                    li
                        key: uid
                        onClick: do (idx, uid) =>
                            (e) =>
                                # justf to illustrate these are bound in closure by the do lambda,
                                c idx
                                c uid
                                @setState
                                    lighted_item: uid
                        style:
                            cursor: 'pointer'
                            background: do (uid) =>
                                c @state.lighted_item
                                c 'and uid', uid
                                if @state.lighted_item is uid then 'magenta' else 'chartreuse'
                            # background: 'chartreuse'
                        item.name
    

    This example works -- I tested it locally. You can check out this example code exactly at my github. Originally the env was only local for my own whiteboard r&d purposes but I posted it to Github for this. It may get written over at some point but you can check out the commit from Sept 8, 2016 to see this.

    More generally, if you want to see how this CS/no-JSX pattern for React works, check out some recent work here. It's possible I will have time to fully implement a POC for this app idea, the stack for which includes NodeJS, Primus, Redis, & React.

    0 讨论(0)
  • 2020-11-28 22:00

    class FrontendSkillList extends React.Component {
      constructor() {
        super();
        this.state = { selectedSkill: {} };
      }
      render() {
        return (
          <ul>
            {this.props.skills.map((skill, i) => (
                <li
                  className={
                    this.state.selectedSkill.id === skill.id ? "selected" : ""
                  }
                  onClick={this.selectSkill.bind(this, skill)}
                  style={{ cursor: "pointer" }}
                  key={skill.id}
                >
                {skill.name}
                </li>
            ))}
          </ul>
        );
      }
    
      selectSkill(selected) {
        if (selected.id !== this.state.selectedSkill.id) {
          this.setState({ selectedSkill: selected });
        } else {
          this.setState({ selectedSkill: {} });
        }
      }
    }
    
    const data = [
      { id: "1", name: "HTML5" },
      { id: "2", name: "CSS3" },
      { id: "3", name: "ES6 & ES7" }
    ];
    const element = (
      <div>
        <h1>Frontend Skill List</h1>
        <FrontendSkillList skills={data} />
      </div>
    );
    ReactDOM.render(element, document.getElementById("root"));
    .selected {
      background-color: rgba(217, 83, 79, 0.8);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>

    @user544079 Hope this demo can help :) I recommend changing background color by toggling classname.

    0 讨论(0)
  • 2020-11-28 22:02

    Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:

    • React events are named using camelCase, rather than lowercase.
    • With JSX you pass a function as the event handler, rather than a string.

    So as mentioned in React documentation, they quite similar to normal HTML when it comes to Event Handling, but event names in React using camelcase, because they are not really HTML, they are JavaScript, also, you pass the function while we passing function call in a string format for HTML, they are different, but the concepts are pretty similar...

    Look at the example below, pay attention to the way event get passed to the function:

    function ActionLink() {
      function handleClick(e) {
        e.preventDefault();
        console.log('The link was clicked.');
      }
    
      return (
        <a href="#" onClick={handleClick}>
          Click me
        </a>
      );
    }
    
    0 讨论(0)
提交回复
热议问题