如何使用react js将onClick绑定到li和它内部的按钮

时间:2016-12-11 17:52:13

标签: reactjs

enter image description here 1.点击列表用户应该看到列表的详细信息  2.点击删除图标用户将显示li里面的删除按钮,在这种情况下point1(上面提到不应该执行)  3.点击删除按钮列表应该执行



var ListComponentWithButton = React.createClass({
  
  getInitialState: function () {
    return {
      'isDelete' : false
    }
  },
  chooseProfile:function (val) {
  //should be executed when user click on li on normal scenario
    console.log('choose',val);
  },
  onDeleteClick: function(val){
  //executed while rendering
  //but it is supposed to be executed on click and onclick is not triggering this function
    console.log(val);
  },
  toggleDelete: function () {
    this.setState({
      'isDelete' : !this.state.isDelete
    })
  },
  render: function(){
  var List =[];
  var ListSource = [{
                    "alias": "John Player Peter England",
                    "id": "1"
                },{
				"alias": "John Player Peter England2",
                    "id": "2"
				}]
  ListSource.map(function (val, index) {
      List.push(
        <li key={index}  onClick={this.chooseProfile.bind(null,val.id)}>
          <div className="profile_list_row">
            <p className="initial">{val.alias}</p>
            <p className='profile_row_icon'>
                <span className="fontcon-arrow-right"></span>
            </p>
            <p className='remove'>
			  <button onClick={this.onDeleteClick(null,this.props.val.id)}>
				<span>Remove</span>
			  </button>
		  </p>
          </div>
        </li>
      );
    },this)
    return (
      <div>
		<ul>
			{List}
		</ul>
		<div>
			<div>
				<div>
				  <button className={' '+(this.state.isDelete ? 'hide':'show')}>
					<span>Add List</span>
				  </button>
				  <button className={' '+(this.state.isDelete ? 'hide':'show')}onClick={this.toggleDelete}>
					<span>Remove list</span>
				  </button>
				  <button className={' '+(this.state.isDelete ? 'show' : 'hide')} onClick={this.toggleDelete}>
					<span className="pad-l10">Done</span>
				  </button>
				</div>
			</div>
		</div>
	  </div>
    )
  }
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

作为事件处理程序,您为元素提供的内容不是函数,而是函数返回的内容,因为您调用它。

例如:

name

应该是

// You have not provided a function but instead
// you are calling a function
<button onClick={this.onDeleteClick(null,this.props.val.id)}>
  <span>Remove</span>
</button>

ES5

// I have provided a function
<button onClick={event => this.onDeleteClick(event.target.value)}>
  <span>Remove</span>
</button>