简体   繁体   English

孙子元素 React 中的箭头语法和绑定问题

[英]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).在上面的示例中,我是从以下文档中得出的,在线寻找解决方案等......甚至不允许我点击按钮(“CLICKED”从未被记录)。

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 this.props.onClick 不是函数

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.当您在<Page />组件中调用<Header />组件时,您有onCLick而不是onClick

Change as the following:更改如下:

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

I hope that helps!我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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