我正在实现一个引导屏幕,用户可以在其中选择 3 个以上的元素,并且在用户点击它之后会保留一个紫色的叠加层。
这是我的代码:
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: this.props.items || [] }
},
componentWillMount: function() {
console.log("componentWillMount()")
this.setState({ items : data })
console.log(data,"data is here");
},
handleClick: function (e, item) {
this.setState({active: true});
},
render: function() {
var listItems = this.state.items.map(function(item) {
return (
<ListItem item={item}/>
);
});
return (
<div className="flex-container">
{listItems}
</div>
);
}
});
/* make the items stateless */
var ListItem = function(props) {
var backgroundImage = {
backgroundImage: 'url(' + props.item.pictureURL + ')'
};
return (
<div className="block-grid-item">
<a className="display-block card text-gray-darker">
<div onClick={handleClick} style={backgroundImage} className="card-img-wrap m-xs-0 placeholder placeholder-landscape">
</div>
<div className="card-meta">
<div className="vesta-hp-gifts-card-title text-gray-darker">{props.item.storeName}</div>
</div>
</a>
</div>
);
}
我在 handleClick 函数中试图保持事件状态时遇到了问题。
这是我的悬停 css 效果
.card-img-wrap::after
{
background-color: #000;
bottom: 0px;
content: "";
left: 0px;
opacity: 0;
position: absolute;
right: 0px;
top: 0px;
}
.card-img-wrap:hover::after
{
background-color: #000;
bottom: 0px;
content: "";
left: 0px;
opacity: 0;
position: absolute;
right: 0px;
top: 0px;
opacity: 0.6;
background-color: #5450DC;
}
为什么这不起作用?如何做到这一点?
最佳答案
您必须将属性传递给 ListItem,handleClick
例如:
render: function() {
var listItems = this.state.items.map(function(item) {
return (
<ListItem handleClick={this.handleClick} item={item}/>
);
});
return (
<div className="flex-container">
{listItems}
</div>
);
}
然后它将在 ListItem
var ListItem = function(props) {
var backgroundImage = {
backgroundImage: 'url(' + props.item.pictureURL + ')'
};
return (
<div className="block-grid-item">
<a className="display-block card text-gray-darker">
<div onClick={props.handleClick} style={backgroundImage} className="card-img-wrap m-xs-0 placeholder placeholder-landscape">
</div>
<div className="card-meta">
<div className="vesta-hp-gifts-card-title text-gray-darker">{props.item.storeName}</div>
</div>
</a>
</div>
);
}
与 active
prop 一样,要么在 ListItem
中控制它,要么通过 parent 的 props 传递它(取决于你的需要)并根据 this prop您应该添加/删除类名。
jsFiddle:https://jsfiddle.net/69z2wepo/67316/
请注意,我在那里使用 ES6 功能以保持上下文,您可以使用绑定(bind)或其他方法,因此 this.handleClick 将引用类函数
关于javascript - 切换 :active class with ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560899/