【问题标题】:react - function in component bodyreact - 组件主体中的功能
【发布时间】:2016-09-20 17:47:11
【问题描述】:

我在推文中看到了这段代码,但我不明白 OnScreenResize 是如何实现的,以便将宽度/高度作为参数提供。我不假设熟悉这些组件,特别是我只想看看它是如何实现的。即子函数如何被调用和传递值

const LeftIcon = ({ onDrawerToggle }) => (
<OnScreenResize debounce={50} bounds={[400,500]}>
   {({ width, height }) => 
    width > smallTablet.value 
    ? Component(onDrawerToggle)
    : OtherComponent()}
</OnScreenResize>
)

【问题讨论】:

    标签: function reactjs higher-order-functions


    【解决方案1】:

    这就是OnScreenResize 的实现方式:

    class OnScreenResize extends Component {
      constructor(props) {
        super(props);
        this.state = {
          width: 0,
          height: 0    
        };
        this.updateWidthAndHeight = this.updateWidthAndHeight.bind(this);
      }
    
      componentWillMount() {
        this.updateWidthAndHeight();
        window.addEventListener('resize', this.updateWidthAndHeight);
      }
    
      componentWillUnmount() {
        window.removeEventListener('resize', this.updateWidthAndHeight);
      }
    
      updateWidthAndHeight() {
        this.setState({
          width: window.innerWidth,
          height: window.innerHeight
        });
      }
    
      render() {
        const { width, height } = this.state;
        return this.props.children({ width, height });
      }
    }
    

    【讨论】:

    • 太棒了,我会接受你的解决方案。我创建了一个小型测试项目,它可以工作。谢谢。
    【解决方案2】:

    我不熟悉OnScreenResize 组件,但看起来它希望它的children 成为一个函数。大多数组件不是这样工作的,但它是一个有效的组件。所以在渲染时,OnScreenResize 计算出宽度和高度,并将其传递给函数this.props.children。然后它会渲染返回的内容,在这种情况下,这将是取决于屏幕宽度的两个组件之一。

    编辑:添加OnScreenResize 组件的示例实现。

    const OnScreenResize = ({children}) => {
      let width = 100 // get width from browser
      let height = 100 // get height from browser
      // TODO: error check that children is actually a function instead of assuming.
      return children({width: width, height: height})
    }
    

    【讨论】:

    • 当 React 添加无状态功能组件(您可以将组件定义为只是一个渲染函数)时,这种语法成为可能。它只是定义了一个匿名函数值来代替传统的 React 组件。
    • 我不希望任何人熟悉该组件,这个问题是假设性的。我只想查看将传入宽度和高度的代码
    猜你喜欢
    • 2020-09-14
    • 2021-08-06
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多