我正在使用react js构建一个Web应用程序。我有CSS设置为当用户选择它突出显示的div时,再次单击时,它取消选择。这是我在jquery中的代码(但需要在反应中编写)。
$("#select-reward-cards .card").click(function () {
$(this).toggleClass('selected');
selectRewardsArray.push($(this).attr('data-value'));
});
$('.goal').click(function () {
$(".goal").removeClass("selected");
$(this).toggleClass('selected');
});
$("#reward-cards .card").click(function () {
if ($(this).hasClass('selected')) {
} else {
$("#reward-cards .card").removeClass("selected");
$(this).toggleClass('selected');
}
});
我的反应代码如下:
var Test = React.createClass({
btnTapped: function(value, thisObj) {
console.log(value);
},
render: function() {
var stationComponents = this.props.stations.map((station, index) => {
return <div onClick={() => this. handleSort(station, $(this))}><img src="img/test.png" />{station}</div>;
});
return <div>{stationComponents}</div>;
}
});
var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];
ReactDOM.render(<Test stations={cards} />, document.getElementById('test-div'));
请原谅我的无知,因为我很擅长做出反应,但是如何在反应中复制jquery功能呢?感谢。
答案 0 :(得分:4)
在反应中,您不要通过检查DOM元素上是否存在类来切换类。您可以更改状态,并且每个元素都可以对新状态(fiddle)做出反应。
我使用三元运算符来更改类,但classnames是更好的解决方案。
var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw", "bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];
var Station = React.createClass({
btnTapped: function() {
this.props.onStationClick(this.props.index);
},
render() {
return (
<div className={ this.props.selected ? 'selected' : '' }
onClick ={ this.btnTapped }>
{ this.props.children }
</div>
);
}
});
var Test = React.createClass({
getInitialState: function() {
return {
selected: null
}
},
onStationClick: function(index) {
this.setState({
selected: index
});
},
render: function() {
var stationComponents = this.props.stations.map((station, index) => (
<Station key={ index }
index={ index }
selected={ this.state.selected === index }
onStationClick = { this.onStationClick }>
{ station }
</Station>
));
return (
<div >{ stationComponents }</div>
);
}
});
ReactDOM.render(
<Test stations={cards} />,
document.getElementById('container')
);
答案 1 :(得分:0)
你也可以用州做。 首先取得您想要选择或取消选择的初始状态
import React from 'react';
class Example extends React.Component {
constructor(props){
super(props);
class : 'selected'
// here initially it will show selected
}
toggleClass(){
this.setState({class: this.state.class == 'selected' ? '' : 'selected'})
}
render(){
return(
<div>
<div>
<button onClick={this.toggleClass.bind(this)} type='button'></button>
</div>
// Now pass state to div class that will toggle everytime user clicks.
<div className={this.state.class}>
// xyz data
</div>
</div>
);
}
}
export default Example;