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处理这类问题,这是偏好问题

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...