Javascript React JS onClick事件处理程序

Javascript React JS onClick事件处理程序,javascript,jquery,reactjs,Javascript,Jquery,Reactjs,我有 我能想到的两种方法是 $('li').on('click', function(){ $(this).css({'background-color': '#ccc'}); }); var TestApp=React.createClass({ getComponent:函数(索引){ $(this.getDOMNode()).find('li:n个子('+index+')).css({ “背景色”:“ccc” }); }, render:function(){ 返回( 组件1

我有


我能想到的两种方法是

$('li').on('click', function(){
    $(this).css({'background-color': '#ccc'});
});
var TestApp=React.createClass({
getComponent:函数(索引){
$(this.getDOMNode()).find('li:n个子('+index+')).css({
“背景色”:“ccc”
});
},
render:function(){
返回(
    组件1 组件2 组件3
); } }); React.renderComponent(,document.getElementById('soln1'));
这是我个人的最爱

var TestApp = React.createClass({
    getComponent: function(index) {
        $(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
            'background-color': '#ccc'
        });
    },
    render: function() {
        return (
            <div>
              <ul>
                <li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
                <li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
                <li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
              </ul>
            </div>
        );
    }
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));
var ListItem=React.createClass({
getInitialState:函数(){
返回{
结果:错
};
},
handleClick:function(){
这是我的国家({
是的
})
},
render:function(){
var isSelected=this.state.isSelected;
变量样式={
“背景色”:”
};
如果(当选){
样式={
“背景色”:“ccc”
};
}
返回(
  • {this.props.content}
  • ); } }); var TestApp2=React.createClass({ getComponent:函数(索引){ $(this.getDOMNode()).find('li:n个子('+index+')).css({ “背景色”:“ccc” }); }, render:function(){ 返回(
    ); } }); React.renderComponent(,document.getElementById('soln2'));
    这是一个

    我希望这有帮助。

    为什么不:

    var ListItem = React.createClass({
        getInitialState: function() {
            return {
                isSelected: false
            };
        },
        handleClick: function() {
            this.setState({
                isSelected: true
            })
        },
        render: function() {
            var isSelected = this.state.isSelected;
            var style = {
                'background-color': ''
            };
            if (isSelected) {
                style = {
                    'background-color': '#ccc'
                };
            }
            return (
                <li onClick={this.handleClick} style={style}>{this.props.content}</li>
            );
        }
    });
    
    var TestApp2 = React.createClass({
        getComponent: function(index) {
            $(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
                'background-color': '#ccc'
            });
        },
        render: function() {
            return (
                <div>
                 <ul>
                  <ListItem content="Component 1" />
                  <ListItem content="Component 2" />
                  <ListItem content="Component 3" />
                 </ul>
                </div>
            );
        }
    });
    React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
    

    您需要将这些
  • 放入一个循环中,并且需要使
    li.on
    li.off
    样式设置您的
    背景色
    如果您使用ES6,下面是一些简单的示例代码:

    onItemClick: function (event) {
    
        this.setState({ selectedItem: event.currentTarget.dataset.id });
        //where 'id' =  whatever suffix you give the data-* li attribute
    },
    
    render: function() {
        return (
            <div>
                <ul>
                    <li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
                    <li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
                    <li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
                </ul>
            </div>
        );
    },
    
    传入数据对象:

    getComponent(object) {
        console.log(object.name);
    }
    
    {this.state.data.map(d=>{
    返回(
    
  • {d.name}
  • )} )}
    以下是如何定义react-onClick事件处理程序,它回答了问题标题。。。使用es6语法

    {this.state.data.map(d => {
        return(
          <li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
        )}
    )}
    
    import React,{Component}来自'React';
    导出默认类测试扩展组件{
    handleClick(e){
    e、 预防默认值()
    console.log(例如target)
    }
    render(){
    返回(
    )
    }
    }
    
    使用ECMA2015。箭头函数使“这”更加直观

    import React, { Component } from 'react';
    
    export default class Test extends Component {
      handleClick(e) {
        e.preventDefault()
        console.log(e.target)
      }
    
      render() {
        return (
          <a href='#' onClick={e => this.handleClick(e)}>click me</a>
        )
      }
    }
    
    从“React”导入React;
    类TestApp扩展了React.Component{
    getComponent(e,索引){
    $(e.target).css({
    “背景色”:“ccc”
    });
    }
    render(){
    返回(
    
    • this.getComponent(e,1)}>Component 1
    • this.getComponent(e,2)}>Component 2
    • this.getComponent(e,3)}>Component 3
    ); } }); React.renderComponent(,document.getElementById('soln1'))`
    这是一种非标准(但并不罕见)的React模式,它不使用JSX,而是将所有内容内联。还有,这是咖啡脚本

    实现这一点的“反应方式”是组件自身的状态:

    c=console.log.bind console

    这个例子有效——我在本地测试了它。 您可以在以下位置查看此示例代码。 最初,env只是出于我自己的白板研发目的而在本地发布的,但我将其发布到Github。它可能会在某个时候被重写,但您可以查看2016年9月8日的提交来了解这一点

    更一般地说,如果您想了解React的CS/no JSX模式是如何工作的,请查看一些最近的工作。我有可能有时间为这个应用想法完全实现一个POC,其堆栈包括NodeJS、Primus、Redis和React

    使用React元素处理事件与处理事件非常相似 关于DOM元素。有一些句法上的差异:

    • React事件使用camelCase命名,而不是小写
    • 使用JSX,可以将函数作为事件处理程序而不是字符串传递
    正如React文档中提到的,它们在事件处理方面与普通HTML非常相似,但是React中使用camelcase的事件名称,因为它们不是真正的HTML,它们是JavaScript,而且,当我们以HTML的字符串格式传递函数调用时,您传递函数,它们是不同的,但是概念非常相似

    请看下面的示例,注意事件传递给函数的方式:

    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
    
    函数ActionLink(){
    函数handleClick(e){
    e、 预防默认值();
    log('已单击链接');
    }
    返回(
    );
    }
    
    您可以使用React.createClone方法。创建您的元素,而不是创建它的克隆。在克隆的创建过程中,您可以注入道具。像这样注入onClick:method属性

    {onClick:()=>this.changeColor(originalElement,index)}

    changeColor方法将设置复制的状态,允许您在过程中设置颜色

    render()
    {
    返回(
    
      {this.state.items.map((val,ind)=>{ 让item=
    • {val}
    • ; 让props={ onClick:()=>此。单击(项,索引), 关键字:ind, ind } 让clone=React.cloneElement(物品,道具,[val]); 返回克隆; })}
    ) }
    从“React”导入React;
    类MyComponent扩展了React.Component{
    getComponent(事件){
    event.target.style.backgro
    
    getComponent(object) {
        console.log(object.name);
    }
    
    {this.state.data.map(d => {
        return(
          <li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
        )}
    )}
    
    import React, { Component } from 'react';
    
    export default class Test extends Component {
      handleClick(e) {
        e.preventDefault()
        console.log(e.target)
      }
    
      render() {
        return (
          <a href='#' onClick={e => this.handleClick(e)}>click me</a>
        )
      }
    }
    
    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'));`
    
    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
    
    function ActionLink() {
      function handleClick(e) {
        e.preventDefault();
        console.log('The link was clicked.');
      }
    
      return (
        <a href="#" onClick={handleClick}>
          Click me
        </a>
      );
    }