react-bits:Render Callback

组件children设为函数

const Width = ({ children }) => children(500)
// The component calls children as a function, with some number of arguments.
// Here, it’s the number 500.
// To use this component, we give it a function as children.

(<Width>
  {width => <div>window is {width}</div>}
</Width>)

// We get this output.
<div>window is 500</div>

//With this setup, we can use this width to make rendering decisions.
(<Width>
{width =>
width > 600
  ? <div>min-width requirement met!</div>
  : null
}
</Width>)

// If we plan to use this condition a lot, we can define another components
// to encapsulate the reused logic.
const MinWidth = ({ width: minWidth, children }) =>
(<Width>
  {width =>
    width > minWidth
      ? children
      : null
  }
</Width>);

// Obviously a static Width component isn’t useful but one that watches
// the browser window is. Here’s a sample implementation.
class WindowWidth extends React.Component {
  constructor () {
    super();
    this.state = { width: 0 };
  }

  componentDidMount() {
    this.setState(
      {width: window.innerWidth},
      () => {
        window.addEventListener(
          "resize",
          ({target}) => this.setState({width: target.innerWidth})
        )
      }
    )
  }

  render() {
    return this.props.children(this.state.width);
  }
}

许多开发者使用HOC处理这类问题,这是偏好问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值