1.基本概念
而 render props 本质实际上是使用到了回调的方式来通信。只不过在传统的 js 回调是在构造函数中进行初始化(使用回调函数作为参数),而在 react 中,现在可以通过 props 传入该回调函数,就是我们所介绍的 render prop。
import React, { Component } from "react";
export class ScrollPos extends Component {
state = {
position: null
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll = e => {
const scrollTop = e.target.scrollingElement.scrollTop;
this.setState((state, props) => {
return { position: scrollTop };
});
};
render() {
return <div className='scroll'>{this.props.children(this.state.position)}</div>;
}
}
export default ScrollPos;
父组件
import React from "react";
import "./App.css";
import ScrollPos from "./component/ScrollPos";
function App() {
return (
<div className="App">
<ScrollPos>
{position => <h1>{"Awesome !".substr(0, position * 15)}</h1>}
</ScrollPos>
<div className="spacer" />
</div>
);
}
export default App;
示例2:
使用 props 传回调函数,需要多少回调就需要设置多少个 prop,比如这里 Auth 子组件既需要登录成功回调又需要登录失败回调。
子组件
const Auth= (props) => {
const userName = getUserName();
if (userName) {
const allProps = {userName, ...props};
return (
<React.Fragment>
{props.login(allProps)}
</React.Fragment>
);
} else {
<React.Fragment>
{props.nologin(props)}
</React.Fragment>
}
};
父组件
<Auth
login={({userName}) => <h1>Hello {userName}</h1>}
nologin={() => <h1>Please login</h1>}
/>
5.浅比较性能优化
class MouseTracker extends React.Component {
// 定义为实例方法,`this.renderTheCat`始终
// 当我们在渲染中使用它时,它指的是相同的函数
renderTheCat(mouse) {
return <Cat mouse={mouse} />;
}
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={this.renderTheCat} />
</div>
);
}
}
* 注:这里也可以直接将 renderTheCat 这个渲染方法变成组件。类似于 下面代码中的 movies
import Movies from "./components/movies";
<Route path="/movies" component={Movies}/>
233