我想在我的状态中使用方法中的变量集,以便我可以获得动态css样式。
当我使用下面的代码时,我没有定义' alpha'错误
我从代码中删除了尽可能多的内容:
constructor(props) {
super(props);
this.state = {
current: 1,
animCardActive: {static object of css properties, works as intended},
// This is where I'd like to use a variable to get dynamic css, only left zIndex for the exemple
animCardInactive: {zIndex: 1000 - (alpha * 100)}
};
_handleStyle(id) {
// The variable I'd like to use in state
let alpha = Math.abs(this.state.current - id);
if(id === this.state.current) {
this.isActive = true;
return this.state.animCardActive;
} else {
this.isActive = false;
return this.state.animCardInactive;
}
}
render() {
return (
<div className='main'>
{cards.map((project, i) => (
<Card
key={i}
style={this._handleStyle(i + 1)}
/>))}
</div>
);
我也尝试过但得到一个zIndex:NaN:
animCardInative: zIndex: 1000 - (Math.abs(this.current - (this.props.key + 1)) * 100)
是否有一个有效的解决方案,或者我是以错误的方式接近这个?
答案 0 :(得分:0)
调用_handleStyle
方法时,您的上下文未定义。要定义this
,您需要以不同方式调用_handleStyle
。现在它失去了背景。您有两种选择:
this
绑定到_handleStyle
constructor(props) {
super(props);
this.state = {
current: 1,
animCardActive: { ... },
canimCardInactive: {zIndex: 1000 - (alpha * 100)}
};
this._handleStyle = this._handleStyle.bind(this); <--- do this
}
this
render() {
return (
<div className='main'>
{cards.map((project, i) => (
<Card
key={i}
style={() => this._handleStyle(i + 1)} <--- or do that
/>))}
</div>
);
}