admin管理员组

文章数量:1406943

I wanna make cool box grow animation (expand) when user clicks on it and I want to do it following way:

  1. user clicks on expand button -> get div dimensions and top/left positions via ref, store it in state and assign div's style to these values
  2. changed expanded state variable and change div's position to fixed, also change left, top values and width, height css values

My problem is in initial div expand click. It seems that both state's changes are rendered in one cycle so I don't see smooth animation on first expand click. I've tried to do it via setState callback, also tried to update expanded in ponentDidUpdate method once div dimensions are in state, nothing worked except delaying expanded set via setTimeout.

Code example via setState callbacks

if (chartsExpanded.get(chart) === "collapsed-end" || !chartsExpanded.get(chart)) {
  this.setState({
    chartsProportions: chartsProportions.set(
      chart,
      Map({
        left: chartProportions.left,
        top: chartProportions.top,
        width: chartProportions.width,
        height: chartProportions.height
      })
    )
  }, () => {
    this.setState({
      chartsExpanded: chartsExpanded.set(chart, "expanded")
    })
  })
}


...
<div
    className={`box customers-per-sources-count ${
      customersPerSourcesCount.loading ? "loading" : ""
    } ${
       chartsExpanded.get("customersPerSourcesCount")
        ? chartsExpanded.get("customersPerSourcesCount")
        : "collapsed-end"
    }`}
    ref={el => {
      this.chartRefs["customersPerSourcesCount"] = el
    }}
    style={{
      left: chartsProportions.getIn(["customersPerSourcesCount", "left"], "auto"),
      top: chartsProportions.getIn(["customersPerSourcesCount", "top"], "auto"),
      width: chartsProportions.getIn(["customersPerSourcesCount", "width"], "100%"),
      height: chartsProportions.getIn(["customersPerSourcesCount", "height"], "100%")
    }}
>

How can I achieve that style from chartsProportions will be rendered before class based on expanded value is changed? I don't want to use setTimeout nor want to update all charts proportions onScroll event etc.

I wanna make cool box grow animation (expand) when user clicks on it and I want to do it following way:

  1. user clicks on expand button -> get div dimensions and top/left positions via ref, store it in state and assign div's style to these values
  2. changed expanded state variable and change div's position to fixed, also change left, top values and width, height css values

My problem is in initial div expand click. It seems that both state's changes are rendered in one cycle so I don't see smooth animation on first expand click. I've tried to do it via setState callback, also tried to update expanded in ponentDidUpdate method once div dimensions are in state, nothing worked except delaying expanded set via setTimeout.

Code example via setState callbacks

if (chartsExpanded.get(chart) === "collapsed-end" || !chartsExpanded.get(chart)) {
  this.setState({
    chartsProportions: chartsProportions.set(
      chart,
      Map({
        left: chartProportions.left,
        top: chartProportions.top,
        width: chartProportions.width,
        height: chartProportions.height
      })
    )
  }, () => {
    this.setState({
      chartsExpanded: chartsExpanded.set(chart, "expanded")
    })
  })
}


...
<div
    className={`box customers-per-sources-count ${
      customersPerSourcesCount.loading ? "loading" : ""
    } ${
       chartsExpanded.get("customersPerSourcesCount")
        ? chartsExpanded.get("customersPerSourcesCount")
        : "collapsed-end"
    }`}
    ref={el => {
      this.chartRefs["customersPerSourcesCount"] = el
    }}
    style={{
      left: chartsProportions.getIn(["customersPerSourcesCount", "left"], "auto"),
      top: chartsProportions.getIn(["customersPerSourcesCount", "top"], "auto"),
      width: chartsProportions.getIn(["customersPerSourcesCount", "width"], "100%"),
      height: chartsProportions.getIn(["customersPerSourcesCount", "height"], "100%")
    }}
>

How can I achieve that style from chartsProportions will be rendered before class based on expanded value is changed? I don't want to use setTimeout nor want to update all charts proportions onScroll event etc.

Share Improve this question asked Dec 2, 2019 at 19:39 ketysekketysek 1,2192 gold badges19 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You just need to pass setState a function instead of an object, to ensure the state changes are applied in order:

this.setState(previousState => ({
  previousChange: "value" 
}))

this.setState(previousState => ({
  afterPreviousChange: previousState.previousChange 
}))

https://reactjs/docs/react-ponent.html#setstate

Another option might be to pass a callback to setState that runs after the state changes have been applied, like:

this.setState({ someChange: "value" }, () => this.setState({ 
  otherChange: "value" 
}))

CSS transitions could help with this too.

Using React state to animate properties is not the right way to do it. State updates will always get batched and you generally don't want to re-render your entire ponent 60 times per second

Store 'expanded' boolean in your state, and change element's class accordingly. Use css to add animations between two states

handleClick = () => {
  this.setState({ expanded: !this.state.expanded })
}

render() {
  return (
    <div
      className={`box ${this.state.expanded ? 'expanded' : ''}`}
      onCLick={this.handleClick}
    />
  )
}

in your css

.box {
    width: 100px;
    height: 100px;
    transition: width 2s;
}

.expanded {
    width: 300px;
}

added based on ments:

What you want to do is:

  1. set position: fixed to your element. This would snap it to the top of the screen instantly, so you need to pick the right top and left values so that position fixed starts off where it was when position was static (default). For that you can use element.getBoundingClientRect()
  2. calculate desired top and left attributes that would make your element appear in the middle of a screen, and apply them
  3. very important: between step 1 and 2 browser has to render the page to apply position and initial top and left values, in order to have something to start animation from. It won't be able to do that if we apply both of these styles synchronously one after another, as page will not render until JS stack frame is clear. Wrap stage 2 logic in setTimeout which will make sure that browser renders at least once with styles applied at stage 1

rough working example:

class Example extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      expanded: false,
      style: {}
    }
  }

  handleClick = (e) => {
    if (!this.state.expanded) {
      const r = e.target.getBoundingClientRect()
      const style = {
        top: r.y,
        left: r.x,
      }
      this.setState({
        expanded: !this.state.expanded,
        style
      })
      setTimeout(() => {
        this.setState({
          style: {
            top: (window.innerHeight / 2) - 50,
            left: (window.innerWidth / 2) - 50,
          }
        })
      })
    } else {
      this.setState({
        expanded: false,
        style: {}
      })
    }
  }

  render() {
    return (
      <div className={'container'}>
        <div className={'empty'} />
        <div className={'empty'} />
        <div className={'empty'} />
        <div
          onClick={this.handleClick}
          className={`box ${this.state.expanded ? 'expanded' : ''}`}
          style={this.state.style}
        />
      </div>
    )
  }
}

and styles.css

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}
.container {
    height: 200vh;
}
.empty {
    height: 100px;
    width: 100px;
    border: 1px solid gray;
}
.box {
    height: 100px;
    width: 100px;
    border: 3px solid red;
    transition: all 0.5s;
}
.expanded {
    position: fixed;
}

本文标签: javascriptReactchange state right after previous state change was renderedStack Overflow