React JS onClick 事件处理程序 [英] React JS onClick event handler
本文介绍了React JS onClick 事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
var TestApp = React.createClass({获取组件:函数(){console.log(this.props);},渲染:函数(){返回(<div><ul><li onClick={this.getComponent}>组件 1</li>
);}});React.renderComponent(
我想为单击的列表元素的背景着色.我怎样才能在 React 中做到这一点?
类似的东西
$('li').on('click', function(){$(this).css({'background-color': '#ccc'});});
解决方案
为什么不:
onItemClick: 函数(事件){event.currentTarget.style.backgroundColor = '#ccc';},渲染:函数(){返回 (<div><ul><li onClick={this.onItemClick}>组件 1</li>
);}
如果你想对它更具反应性,你可能希望将所选项目设置为其包含 React 组件的状态,然后引用该状态以确定 render
中项目的颜色:
onItemClick: 函数(事件){this.setState({ selectedItem: event.currentTarget.dataset.id });//where 'id' = 你给 data-* li 属性的任何后缀},渲染:函数(){返回 (<div><ul><li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ?开":关"}>组件1<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ?开":关"}>组件2<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ?开":关"}>组件3
);},
您想将那些 放入一个循环中,并且您需要制作
li.on
和 li.off
样式设置您的 background-color
.
I have
var TestApp = React.createClass({
getComponent: function(){
console.log(this.props);
},
render: function(){
return(
<div>
<ul>
<li onClick={this.getComponent}>Component 1</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp />, document.body);
I want to color the background of the clicked list element. How can I do this in React ?
Something like
$('li').on('click', function(){
$(this).css({'background-color': '#ccc'});
});
解决方案
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
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>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.
这篇关于React JS onClick 事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!