React JS onClick事件处理程序 [英] React JS onClick event handler
本文介绍了React JS onClick事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
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);
我想为点击的列表元素的背景着色。我怎么能在React中做到这一点?
I want to color the background of the clicked list element. How can I do this in React ?
类似
$('li').on('click', function(){
$(this).css({'background-color': '#ccc'});
});
推荐答案
为什么不呢:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
如果你想了解更多React-ive,你可能想要将所选项目设置为其包含的React组件的状态,然后引用该状态以确定渲染中项目的颜色
:
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>
);
},
当然,你想把那些< li>
进入循环,你需要制作 li.on
和 li.off
样式设置背景颜色
。
Of course, 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屋!
查看全文