我尝试使用反应路由器4向我的应用添加页面转换。由于某些原因,函数import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './containers/App';
render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
,import React, { Component } from 'react';
import { Route, Link } from 'react-router-dom';
import TransitionGroup from 'react-transition-group/TransitionGroup';
import Home from '../components/home/Home';
import Users from '../components/users/Users';
const firstChild = (props) => {
const childrenArray = React.Children.toArray(props.children);
return childrenArray[0] || null;
};
class App extends Component {
render() {
return (
<div className="App">
<ul className="TopBar">
<Link to="/">Home</Link>
<Link to="/users">Users</Link>
</ul>
<Route
exact
path="/"
children={({ match, ...rest }) => (
<TransitionGroup component={firstChild}>
{match && <Home {...rest} />}
</TransitionGroup>
)} />
<Route
path="/users"
children={({ match, ...rest }) => (
<TransitionGroup component={firstChild}>
{match && <Users {...rest} />}
</TransitionGroup>
)} />
</div>
);
}
}
export default App;
未被调用。有人知道为什么吗?
index.js
import React, { Component } from 'react';
const AnimatedWrapper = WrappedComponent => class AnimatedWrapper extends Component {
constructor(props) {
super(props);
this.state = {
animate: 0
};
}
componentWillAppear(cb) {
console.log('WillAppear');
this.setState({
animate: 1
});
cb();
}
componentWillEnter(cb) {
console.log('WillEnter');
this.setState({
animate: 1
});
cb();
}
componentWillLeave(cb) {
console.log('WillLeave');
this.setState({
animate: 0
});
setTimeout(() => cb(), 175);
}
render() {
console.log(this.state.animate);
const style = {
opacity: `${this.state.animate}`,
};
return (
<div style={style} className="animated-page-wrapper">
<WrappedComponent {...this.props} />
</div>
);
}
};
export default AnimatedWrapper;
部件/ App.js:
import React, { Component } from 'react';
import AnimatedWrapper from '../animated/AnimatedWrapper';
class HomeComponent extends Component {
render() {
return (
<div className="page">
<h1>Home</h1>
<p>Hello from the home page!</p>
</div>
);
}
}
const Home = AnimatedWrapper(HomeComponent);
export default Home;
组件/ AnimatedWrapper.js
import React, { Component } from 'react';
import AnimatedWrapper from '../animated/AnimatedWrapper';
class UsersComponent extends Component {
render() {
return (
<div className="page">
<h1>Users</h1>
<p>Hello from users page!</p>
</div>
);
}
}
const Users = AnimatedWrapper(UsersComponent);
export default Users;
组件/ Home.js
Match case
部件/ Users.js:
Regular expression
答案 0 :(得分:0)
TransitionGroup
无法以这种方式运作。它是低级别组件,无法到达componentWillEnter()
和<Switch>
内的<Route>
挂钩。
您可以改为使用ReactCSSTransitionGroup
。