, burada bir örnek kabul edilen cevapta açıklandığı gibi aynı işlevselliği vermek için başka bir bileşeni saran daha yüksek bir sipariş bileşeni. Kalıcı olarak kalan tüm zaman aşımlarını düzgün bir şekilde temizler ve çocuk bileşenine bunu sahne aracılığıyla yönetmek için bir API verir.
Bu in katmalar değiştirmek için tavsiye edilen bir yol olan ES6 sınıflarını kullanan ve component composition Timeout.jsx olarak 2017.
MyComponent.jsx olarak
import React, { Component } from 'react';
const Timeout = Composition => class _Timeout extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.timeouts = [];
}
setTimeout() {
this.timeouts.push(setTimeout.apply(null, arguments));
}
clearTimeouts() {
this.timeouts.forEach(clearTimeout);
}
componentWillUnmount() {
this.clearTimeouts();
}
render() {
const { timeouts, setTimeout, clearTimeouts } = this;
return <Composition
timeouts={timeouts}
setTimeout={setTimeout}
clearTimeouts={clearTimeouts}
{ ...this.props } />
}
}
export default Timeout;
import React, { Component } from 'react';
import Timeout from './Timeout';
class MyComponent extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
// You can access methods of Timeout as they
// were passed down as props.
this.props.setTimeout(() => {
console.log("Hey! I'm timing out!")
}, 1000)
}
render() {
return <span>Hello, world!</span>
}
}
// Pass your component to Timeout to create the magic.
export default Timeout(MyComponent);
hala sadece JS, bunu React olmadan yaptığınız gibi yaparsınız. –
'clearTimeout', zamanlayıcı kimliğini sakladığınızı varsayar. – WiredPrairie