在React中应用动画

时间:2018-01-15 07:33:43

标签: css reactjs

我正在尝试创建更多节目并使用React显示效果较差。但是我想要应用一些动画。

我有React JS代码如下:

const FEATURES = ["Light alloy wheels in general", 
        "Leather upholstery", 
        "Xenon-light", 
        "mp3 Player", 
        "Navigation system", 
        "Roof: other", 
        "Power steering", 
        "Automatic climate control", 
        "Cruise control", 
        "Bluetooth interface", 
        "Park Distance Control rear", 
        "Heated seat driver"];
const MAX_HEIGHT = 150;

class Test extends React.Component {
        constructor(props){
        super(props);

      this.state = {
        moreSpecsButton: false,
        lessSpecsButton: false,
        specsBoxStyles: {}
      }
    }

    componentDidMount(){
        let height = document.getElementById("child-ref").clientHeight;
        if(height > MAX_HEIGHT){
            this.setState({moreSpecsButton: true, specsBoxStyles: {height: MAX_HEIGHT, overflowY: "hidden"}})
        }else{
            this.setState({specsBoxStyles: {height: height, overflowY: "visible"}})
        }
    }

    showMore(){
        let height = document.getElementById("view-ref").clientHeight;
        this.setState({moreSpecsButton: false, specsBoxStyles: {height: height, overflowY: "visible"}, lessSpecsButton: true})
    };

    showLess(){
        this.setState({moreSpecsButton: true, specsBoxStyles: {height: MAX_HEIGHT, overflowY: "hidden"}, lessSpecsButton: false})
    };

    renderMoreLessButton(){
        if(this.state.moreSpecsButton && !this.state.lessSpecsButton){
            return <div className="moreLessButton clearfix" onClick={this.showMore.bind(this)}>Show more</div>;
        }

        if(this.state.lessSpecsButton && !this.state.moreSpecsButton){
            return <div className="moreLessButton clearfix" onClick={this.showLess.bind(this)}>Show less</div>;
        }

    }

    render(){
        return (
        <div>
            <div className="wrapper-box clearfix">
                <div id="child-ref" className="child-box clearfix" ref="child-ref" style={{...this.state.specsBoxStyles}}>
                        <div id="view-ref">
                    {FEATURES.map(feature => <div>{feature}</div>)}
                </div>
                </div>
            </div>
            {this.renderMoreLessButton()}
        </div>
      )
    }
}

React.render(<Test />, document.getElementById('container'));

css类如下:

.child-box{
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

Here is the fiddle.

正如您在小提琴中看到的那样,点击show less时的动画很不错,就像它应该的那样,但是当我点击show more时它就不那么好了。

知道怎么解决吗?

1 个答案:

答案 0 :(得分:1)

overflowY中的

showMore()应为hidden