React fade in element

帅比萌擦擦* 提交于 2019-12-18 13:11:40

问题


I have a Basket component which needs to toggle a BasketContents component when clicked on. This works:

constructor() {
    super();
    this.state = {
      open: false
    }
    this.handleDropDown = this.handleDropDown.bind(this);
  }
  handleDropDown() {
    this.setState({ open: !this.state.open })
  }
    render() {
        return(
            <div className="basket">
                <button className="basketBtn" onClick={this.handleDropDown}>
                    Open
                </button>
              {
                this.state.open
                ?
                <BasketContents />
                : null
              }
            </div>
        )
    }

It uses a conditional to either display the BasketContents component or not. I now want it to fade in. I tried adding a ComponentDidMount hook to BasketContents to transition the opacity but that doesn't work. Is there a simple way to do this?


回答1:


An example using css class toggling + opacity transitions:
https://jsfiddle.net/e7zwhcbt/2/

Here's the interesting CSS:

.basket {
  transition: opacity 0.5s;
  opacity: 1;
}
.basket.hide {
  opacity: 0;
  pointer-events:none;
}

And the render function:

render() {
    const classes = this.state.open ? 'basket' : 'basket hide'
    return(
      <div className="basket">
        <button className="basketBtn" onClick={this.handleDropDown}>
          {this.state.open ? 'Close' : 'Open'}
        </button>
        <BasketContents className={classes}/>
      </div>
    )
  }



回答2:


I would use react-motion like this:

<Motion style={{currentOpacity: spring(this.state.open ? 1 : 0, { stiffness: 140, damping: 20 })}}>
    {({currentOpacity}) =>
        <div style={{opacity: currentOpacity}}>
            <BasketContents />
        </div>
    }
</Motion>

I haven't tested it, but it should work.




回答3:


I used react-animate-on-scroll personally. major props (pun intended) to its creator @dbramwell on github. Sorted my criteria in about 5 minutes. BOOM. 🎉



来源:https://stackoverflow.com/questions/41852818/react-fade-in-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!