React Visible + Add class

时间:2018-03-17 17:48:34

标签: reactjs class add

这是有效的:

var onChange = function (isVisible) {
    console.log('Element is now %s', isVisible ? 'visible' : 'hidden');
    if(isVisible = 'visible'){
        //here I need add class
    }
};

VisibilitySensor位于div className = 需要的内部组件需要中。

<VisibilitySensor onChange={onChange}/>

代码运行良好,渲染后我可以看到console.log。 所以。我的问题是什么。

我不会添加课程动画fadeInUp if isVisible ='visible'

如何将此课程添加到需要 className React?

如果有帮助,这里是所有代码:

https://pastebin.com/bnTKbXC4

3 个答案:

答案 0 :(得分:0)

我不知道你是否在管理国家。但看起来这是有状态的组成部分,为什么不呢。

// just below this line -  class Needs extends React.Component 
state = {
    NeedsBrother: false // setting this variable to false initially
}

然后

var onChange = function (isVisible) {
    console.log('Element is now %s', isVisible ? 'visible' : 'hidden');
    if(isVisible = 'visible'){
        this.setState(prevState => {
            NeedsBrother: true
        })
    }
};

并在你的渲染功能中

<div className={`Need ${this.state.NeedsBrother}`}>

答案 1 :(得分:0)

您是否已将NeedsBrother声明为状态变量。

this.state={NeedsBrother:false}

答案 2 :(得分:0)

这是对代码的重构,我不确定它是否会起作用。

class Needs extends React.Component{


    constructor(props)
    {
        super(props);
        this.state = {
            Need: 'Need'
            };

        this.onChange = this.onChange.bind(this);
    }

    onChange(isVisible)
    {
        console.log('Element is now %s', isVisible ? 'visible' : 'hidden');
        if(isVisible = 'visible')
        {
            this.setState( {Need : 'Need ' + ' animated fadeIn' } );
        }
        else
        {
            this.setState( {Need : 'Need ' } );
        }
    }

    render()
    {
        var VisibilitySensor = require('react-visibility-sensor');

        return(
            <div className ={this.state.Need}>

                <VisibilitySensor onChange={this.onChange}/>

                <div className ="Section_Text">
                    <h1>Solutions tailored to your needs</h1>
                    <p><b>Creating experience in real & digital world.</b></p>
                    <p>
                        Cooperation with a lot of designers, photographers,
                        programmist & specialists from various field allows
                        to create effective solutions for your business goals.</p>
                </div>

                <img src={bulb} />
            </div>
        )
    }
}