因此,經過一番休息後,我決定是'學生教學生'(書面指導和主演我)的另一章的時間。
爲了更加簡潔地回答我自己的問題,transitionend事件偵聽器將一個偵聽器附加到一個元素,並在轉換結束時觸發一個回調函數。我遇到的問題是這是異步的,因此,將它放在componentWillUpdate中將不起作用,因爲在轉換完成之前DOM將呈現。我當前的解決方法是讓按鈕單擊調用包含事件偵聽器的函數,並使trinaSync的回調函數改變組件的狀態。這樣,直到轉換完成才能完成渲染。
代碼:
class Button2 extends React.Component {
constructor(props){
super(props)
this.onClickHandler = this.onClickHandler.bind(this)
}
onClickHandler(){
this.props.onClick("Button2")
}
render() {
return (
<button onClick={this.onClickHandler} id="button2">
BUTTON2!!
</button>
)
}
}
class Button1 extends React.Component {
constructor(props){
super(props)
this.onClickHandler = this.onClickHandler.bind(this)
}
onClickHandler(){
this.props.onClick('Button1')
}
render() {
return (
<button onClick={this.onClickHandler} id="button1">
BUTTON1!!
</button>
)
}
}
class App extends React.Component {
constructor(props){
super(props)
this.state = {
showButton : true,
hide: false
}
this.changeButtonState = this.changeButtonState.bind(this)
this.getButton = this.getButton.bind(this)
this.transitionEndEventName = this.transitionEndEventName.bind(this)
this.hideApp = this.hideApp.bind(this)
this.removeEvent = this.removeEvent.bind(this)
}
getButton() {
if (this.state.showButton){
return <Button1 onClick={this.hideApp}/>
} else {
return <Button2 onClick={this.hideApp}/>
}
}
transitionEndEventName() {
var el = document.createElement('div')//what the hack is bootstrap
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return transEndEventNames[name];
}
}
return false // explicit for ie8 ( ._.)
}
hideApp(button) {
var app = document.getElementById('main')
var transitionEnd = this.transitionEndEventName()
app.addEventListener(transitionEnd, this.removeEvent, false)
app.classList.contains('show-element') ? app.classList.remove('show-element') : null
app.classList.add('remove-element')
}
removeEvent(){
console.log('hey')
var app = document.getElementById('main')
var transitionEnd = this.transitionEndEventName()
app.removeEventListener(transitionEnd, this.removeEvent, false)
this.changeButtonState()
}
changeButtonState(button) {
this.setState({
showButton: !this.state.showButton,
hide: true
})
}
componentDidUpdate(){
var app = document.getElementById('main')
app.classList.contains('remove-element') ? app.classList.remove('remove-element') : null
app.classList.add('show-element')
}
render(){
var button = this.getButton()
return (
<div id="button-container">
{button}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('main'))
codepen (檢查codepen
如果有人讀這所看見的codepen你會發現正確的道路上應用的過渡,但是沒有很好的時候如果有人知道這是爲什麼我會很高興知道。 –