![](/img/trans.png)
[英]React: conditionally render element with ref as a prop, sometimes ref is lost
[英]React ref for a react element passed as a prop, dynamic event
我正在構建一個下拉組件,該組件將按鈕元素作為道具。 這是我要做什么的簡短描述:
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>
)
}
}
簡而言之,如果我有一個帶有react元素的變量,
1.如何獲得對作為道具傳遞的按鈕dom節點的引用? (我需要將其傳遞給dom-align
)。
2.如何將事件偵聽器附加到傳遞的button元素上?
這就是通過箭頭功能組件來實現的,並傳遞引用和事件偵聽器。
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 />
//For creating reference const (inside constructor)
ref_name = React.createRef();
// For connect ref to html
<tag ref={this.ref_name}></tag>
// For creating event create a class method
handleClick(){}
//Register it inside constructor
this.handleClick = this.handleClick.bind(this);
// attach with html
<button onClick={this.handleClick}>Click</button>
class App extends React.Component {
constructor(props){
super(props);
this.button_ref = React.createRef();
this.handleClick = this.handleClick.bind(this);
}
handleClick(event){
//write your code...
}
render() {
return (
<Dropdown trigger={<button ref={this.button_ref} onClick={this.handleClick}>Click me</button>}>
dropdown content
</Dropdown>
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.