Answer the question
In order to leave comments, you need to log in
How to implement interaction between React and non-React part of the code on the page? And how to add a React method to an element?
I wondered:
If part of the page is on React, and the other is not, but somehow you need to interact.
How best to implement.
Also, what is the best way to add methods?
Or are they not boring, and if so, what is the alternative?
Like this:
let element = (
<h1>
Hello
</h1>
);
element.someMethod=()=>{};
element.someMethod();
Answer the question
In order to leave comments, you need to log in
The best way to do this is to use the component as a class:
class MyElement extends Component {
componentDidMount() {
// начиная с этого момента у вас есть доступ к
// this.container - это ссылка на DOM ноду (или реакт-элемент)
jQuery(this.container) // например используем джейквери
// или вызовем метод элемента
// выведет в консоль 'Wow, so super!'
this.componentWithMethod.mySuperMethod()
}
handle3dPartyContainerRef = node => {
this.container = node
}
handleComponentRef= node => {
this.componentWithMethod= node
}
render() {
return (
<div>
<h1>Hello!</h1>
<div ref={this.handle3dPartyContainerRef} />
<ComponentWithMethod ref={this.handleComponentRef} />
</div>
)
}
}
class ComponentWithMethod extends Component {
mySuperMethod = () => {
// Вот так можно добавить метод к элементу
// вызывать его можно если получить ссылку на установленный в DOM элемент
console.log('Wow, so super!')
}
render() {
return (
<span>just a node</span>
)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question