semantic-ui - 作为 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
}
解决方案
这里的关键是克隆元素
ChildComponent extends Component {
functionToCall = () => { console.log('hello') }
this.Trigger = React.cloneElement(
this.props.trigger,
{ onClick: this.functionToCall }
)
}
推荐阅读
- python-3.7 - 如何解决“TypeError:只能将整数标量数组转换为标量索引”的问题
- c - 我们可以为 gcc 上的特定功能添加 `-fcall-used-REG` 吗?
- node.js - 从变量声明一个nodejs const?
- java - 声明一堆相似变量的最少行
- php - 如何在 PHP 中的查询中添加函数
- javascript - 我似乎无法弄清楚如何进行字符串插值;代码排练习
- python - 定义vigenere的python vigenere问题
- prolog - Ensure Input List Minimum Length Prolog
- html - 如何制作 3 个响应式列?
- typescript - 打字稿导入依赖与类