U
U
uzi_no_uzi2019-08-21 12:07:08
React
uzi_no_uzi, 2019-08-21 12:07:08

Why doesn't calling a function passed through props work?

The parent component has this function

this.mobileMenuOpen = () => {

    console.log('тут')

    this.setState({
        mobileMenuShow: !this.state.mobileMenuShow,
    })

    console.log(this.state.mobileMenuShow)
}

Also inside the parent component is this child:
<BackgroundWave 
    link={this.waveBackground} 
    link2={this.waveBackgroundWrapper}
    onMobileMenuOpen={this.mobileMenuOpen}
    mobileMenuOpen={this.state.mobileMenuShow}
/>

The function above is passed to the child component. This function is then called in the child component:onMobileMenuOpen={this.mobileMenuOpen}
function BackgroundWave(props) {

    let classBackground, classArrow = '';
    if(props.mobileMenuOpen) {
        classBackground = 'background-wave background-wave--opened';

    } else {
        classBackground = 'background-wave';
    }




    return (
        <div className={classBackground} ref={props.link2}>
            <canvas ref={props.link} id='background-animation' className='background-wave__item'></canvas>
            <div className='background-wave__opener-wrap' onClick={props.onMobileMenuOpen}>
                <svg className='background-wave__opener'>
                    <use xlinkHref='img/icons/sprite.svg#mobile-opener' />
                </svg>
            </div>
        </div>
    );

  }

But the call does not work, I can not understand why, I tried to call in various ways.
onClick={props.onMobileMenuOpen()}
onClick={() => {props.onMobileMenuOpen}}

But it did not help

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Churmanov, 2019-08-21
@CrazyNiger

Passing a function and calling it looks correct. Perhaps the event onClickon the element does not occur, due to the fact that the click itself goes to svg. Do an experiment, do this:<div>
and check if there is a result in the log on click.

J
justadumb, 2019-08-21
@justadumb

Show the full code of the parent component, is the mobileMenuOpen function declared in the constructor or what? If not, why is this there?

P
Pavel Didenko, 2019-08-21
@Dasslier

If the parent component is a class, then the method is declared like this: If it is a functional component, then this: Do this and it should work, or if it doesn’t work, put the full code in the sandbox

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question