简体   繁体   中英

How can I use a variable in React's state?

I would like to use a variable set in a method in my state so I can get dynamic css styles in return.

When I use the code below, I have an 'alpha is not defined' error

I removed as much as I could from the code :

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>
);

What I also tried but get a zIndex: NaN :

  • Using this syntax in my state :

animCardInative: zIndex: 1000 - (Math.abs(this.current - (this.props.key + 1)) * 100)

  • Defining Alpha in my state (although it doesn't look look good practice) as Alpha: Math.abs(this.current - this.props.id)

Is there a valid solution to this or am I approaching this the wrong way ?

Your context is not defined when you call your _handleStyle method. For this to be defined, you need to invoke _handleStyle differently. Right now it loses the context. You have two options:

Option 1: Bind this in constructor to _handleStyle

constructor(props) {
  super(props);
  this.state = {
    current: 1,
    animCardActive: { ... },
    canimCardInactive: {zIndex: 1000 - (alpha * 100)}
  };

  this._handleStyle = this._handleStyle.bind(this); <--- do this
}

Option 2: Bind this during invocation

render() {
  return (
    <div className='main'>
      {cards.map((project, i) => (
        <Card
          key={i}
          style={() => this._handleStyle(i + 1)} <--- or do that
        />))}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM