简体   繁体   中英

Issues With Arrow Syntax and Binding in React for Grandchild Element

I'm trying to create a test page and I'm having trouble with getting some buttons to work.

import React from 'react'
import { Dropdown, Icon, Menu, Segment } from 'semantic-ui-react'

export class Page extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            sidebarVisible: false
        }
    }

    render() {
        return (
            <Header name='test' onCLick={this.handleIconClick}/>
        )
    }

    handleIconClick = () => {

        console.log('CLICKED');
        let visible = !this.state.sidebarVisible;
        this.setState({sidebarVisible: visible});

    }

}

export class Header extends React.Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            iconName: this.props.visible ? 'angle double left' : 'angle double right'
        };
        console.log(this.props)
    }

    render() {
        return (
            <div>
                <Menu>
                    <Menu.Item onClick={this.props.onClick}>
                        <Icon name={this.state.iconName}/>
                    </Menu.Item>
                </Menu>
            </div>
        )
    }
}

In the above example which I've arrived at from following documentation, looking online for solutions, etc... does not even allow me to click the button ("CLICKED" is never logged).

When I change

<Menu.Item onClick={this.props.onClick}>

to

<Menu.Item onClick={() => this.props.onClick()}>

I get an error stating that:

this.props.onClick is not a function

I've spent quite some time on this so your help would be greatly appreciated.

Thanks.

It's not related to arrow syntax. You have onCLick instead of onClick when you call <Header /> component in <Page /> component.

Change as the following:

<Header name='test' onClick={this.handleIconClick} />

I hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM