如何将回调函数传递给父级

How to pass callback functions to parent

假设我们有一个 Container 组件如下。

class Container extends React.Component {
    handleClose = () => {
        // need to ask 'Content' is it okay with closing
        const isContentAgree = /* */;
        if (isContentAgree) this.props.onClose();
    };

    render () {
        const {content: Content} = this.props;
        return (
            <button onClick={this.handleClick}>Close</button>
            <Content {/* some container-specific props */} />
        );
    }
}

用法:

<Container content={SomeComponent}/>

在这种情况下,如何将回调函数从 SomeComponent 传递到 Container?单击容器中的按钮并且 returns 一个布尔值时将调用此回调。

您需要将 isContentAgree 保留在 state 中,您可以通过函数将 isContentAgree 切换到子组件。

class Container extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
              isContentAgree: false
            }
        }

        toggleContentAgree = (e) => {
            this.setState({ isContentAgree: e.target.value })
        }

        handleClose = () => {
            // need to ask 'Content' is it okay with closing
            const isContentAgree = this.state.isContentAgree;
            if (isContentAgree) this.props.onClose();
        };

        render () {
            const {content: Content} = this.props;
            return (
                <button onClick={this.handleClose}>Close</button>
                <Content toggleContentAgree={this.toggleContentAgree} />
            );
        }
    }

您可以使用:

React.cloneElement(SomeComponent, [props...])

并作为 "props" 传递更新容器状态的函数。

你可以简单地将回调函数作为 prop 传递给组件。

<Content onHide={handleClose} />

在组件中,您必须根据需要调用 props.onHide 函数。

您应该使用商店 (Redux/Mobx/ContextAPI)。这是最理想的方式。

但是...

你仍然可以传递回调函数:

class Container extends React.Component {
    render () {
        const {content: Content, callback} = this.props;
        return (
            <button onClick={this.handleClick}>Close</button>
            <Content onSomething={callback} {/* ... */} />
        );
    }
}

<Container content={SomeComponent} callback={someCallbackFunction}/>