访问作为 Prop 传递的组件的事件

Access Event Of Component That Is Passed As Prop

我将 React Component as a Prop 传递给 child。 该组件有一个 event。 在 child 组件中,我想访问该事件并将其绑定到 child 中的方法。我该怎么做?

我经常使用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>
        )
    }
}

如何访问触发器组件并将其 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
}

在 React 中,数据从父级流向子级。如果有多个子组件具有需要触发父组件更改的事件,则必须在子组件中触发回调函数。

父组件:

handleOpen = () => { // do something }
(...)
<childComponent onClickCallback={this.handleOpen}

在子组件中:

<button onClick={this.props.onClickCallback}> Click to close</button>

this.handleOpen作为prop传入,在子组件中作为prop调用,会在父组件中触发function,你可以随心所欲地处理数据。

这是你要的吗?

这里的关键是克隆元素

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

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