加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react-bits:Render Callback

发布时间:2020-12-15 07:26:03 所属栏目:百科 来源:网络整理
导读:组件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.(Wi

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读