首页 > 解决方案 > 作为 Prop 传递的组件的访问事件

问题描述

我将React 组件作为道具传递给孩子。该组件有一个事件。在子组件中,我想访问该事件并将其绑定到子组件中的方法。我怎样才能做到这一点 ?

我经常使用Semantic-UI React Modal如下:

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalOpen: false
        }
    }    

    handleOpen = () => this.setState({ modalOpen: true })

    handleClose = () => this.setState({ modalOpen: false })

    render(){
        return(
            <Modal 
                onClose={this.handleClose}
                open={this.state.modalOpen}
                trigger={<Button onClick={this.handleOpen}>Gandalf</Button>}>
                <Modal.Header>Balrog</Modal.Header>
                <Modal.Content>
                    <h1>You shall not pass!</h1>
                    {/* 
                    Some form that closes Modal on success
                    onSuccess : this.handleClose 
                    */}
                    <Button onClick={this.handleClose}>Grrrrr</Button>
                </Modal.Content>
            </Modal>
        )
    }
}

export default Example

现在我想让它可重复使用

import React, { Component } from 'react'
import { Modal } from 'semantic-ui-react'

class ReusableModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalOpen: false
        }
    }    

    handleOpen = () => this.setState({ modalOpen: true })

    handleClose = () => this.setState({ modalOpen: false })

    render(){
        return(
            <Modal 
                onClose={() => this.handleClose}
                open={this.state.modalOpen}
                {/* 
                    How to access onClick event on trigger prop content ?  
                    this.prop.trigger can be a Button or a Menu.Item
                */}
                {...this.props}>
                {this.props.children}
            </Modal>
        )
    }
}

如何访问 trigger prop 组件并将其 onClick 事件绑定到 handleOpen 方法?

编辑 :

更准确地说,这是我正在寻找的

<ChildComponent trigger={<Button>This button should fire a function defined in child component</Button>} />


ChildComponent extends Component {
    functionToCall = () => { console.log('hello') }
    // I would like to :
    // let myButton = this.props.trigger
    // myButton.onClick = functionToCall
}

标签: semantic-uireact-propscompositionreact-componentreact-class-based-component

解决方案


这里的关键是克隆元素

ChildComponent extends Component {
    functionToCall = () => { console.log('hello') }

    this.Trigger = React.cloneElement(
        this.props.trigger,
        { onClick: this.functionToCall }
    )   
}

推荐阅读