[译] 使用 Render props 吧!

https://juejin.im/post/5a3087746fb9a0450c4963a5

render prop 是一个用于告知组件需要渲染什么内容的函数 prop
这也是逻辑复用的一种方式

在这篇文章看来
该技术规避了所有 mixin 和 HOC 会面对的问题:

  • ES6 class。不成问题,我们可以在 ES6 class 创建的组件中使用 render prop。
  • 不够直接。我们不必再担心 state 或者 props 来自哪里。我们可以看到通过 render prop 的参数列表看到有哪些 state 或者 props 可供使用。
  • 名字冲突。现在不会有任何的自动属性名称合并,因此,名字冲突将全无可乘之机。
const withMouse = (Component) => {
  return class extends React.Component {
    render() {
      return <Mouse render={mouse => (
        <Component {...this.props} mouse={mouse}/>
      )}/>
    }
  }
}

亦有如下例子作参考;

class MouseTracker extends React.Component {
    constructor(props) {
        super(props);
        this.state = { x: 0, y: 0 };
    }

    handleMouseMove = (event) => {
        this.setState({
            x: event.clientX,
            y: event.clientY
        });
    }

    render() {
        return (
            <div onMouseMove={this.handleMouseMove}>
               {this.props.render(this.state)}
            </div>
        );
    }
}
function withMouse(Component){
 return (
     (props)=><MouseTracker render={mouse=><Component {...props} {...mouse}/>}/>
 )
}
let App = withMouse(props=>(
    <>
      <h1>移动鼠标!</h1>
      <p>当前的鼠标位置是 ({props.x}, {props.y})</p>
    </>
));
ReactDOM.render(<App/>, document.getElementById('root'));

作者:吴晓军
链接:https://juejin.im/post/5a3087746fb9a0450c4963a5
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值