javascript - 作为道具传递的反应元素的反应参考,动态事件
问题描述
我正在构建一个下拉组件,它获取一个按钮元素作为道具。这是对我正在尝试做的事情的简短描述:
class Dropdown extends React.Component {
render() {
let button = this.props.trigger;
// How do I get a ref to the button native DOM node?
// How can I attach a react event to the button?
}
}
这就是我想使用它的方式:
class App extends React.Component {
render() {
return (
<Dropdown trigger={<button>Click me</button>}>
dropdown content
</Dropdown>
)
}
}
简而言之,如果我有一个带有反应元素的变量,
1.如何获得作为道具传递的按钮 dom 节点的引用?(我需要将其传递给dom-align
)。
2. 如何将事件侦听器附加到传递的按钮元素?
解决方案
这就是您可以使用按钮的箭头功能组件并传递 ref 和事件侦听器的方法。
const Button = ({buttonRef, onEvent}) => <button ref={buttonRef} onEvent />
class Parent extends Component {
methodForButton = e => {...}
render() {
return (
<Dropdown
propButton={
<Button buttonRef={el => this.buttonElement = el} onEvent={this.methodForButton} />
}
>{...}<Dropdown />
);
}
}
您也可以将按钮作为孩子而不是道具传递
<Dropdown><Button /><Dropdown />
推荐阅读
- mysql - where 子句中的 Deep SubQuery Unknow 列
- html - 如何在文本颜色中间居中文本
- typescript - TypeScript 模块解析不适用于 Cucumber-js
- wordpress - 我什么时候不能在 Wordpress 的主题编辑器上更新我的文件?
- java - 使用 C# 进行 MDNS 服务注册
- android - click_action 没有启动指定的活动
- sql - 浮动到字符串没有科学记数法:SQL Server
- python-3.x - 在 python 中生成 csv 文件 - 使用带有多维列表的列表的 zip
- javascript - Chart.js 的缩放功能
- mysql - 需要获取最后一个 id 的记录