反应 - 组件主体中的功能
react - function in component body
我在推文中看到了这段代码,但我不明白 OnScreenResize 是如何实现的,因此 width/height 被作为参数提供。我不假设您熟悉这些组件,特别是我只是想看看它是如何实现的。即如何调用子函数并传递值
const LeftIcon = ({ onDrawerToggle }) => (
<OnScreenResize debounce={50} bounds={[400,500]}>
{({ width, height }) =>
width > smallTablet.value
? Component(onDrawerToggle)
: OtherComponent()}
</OnScreenResize>
)
我不熟悉 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})
}
这是 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 });
}
}
我在推文中看到了这段代码,但我不明白 OnScreenResize 是如何实现的,因此 width/height 被作为参数提供。我不假设您熟悉这些组件,特别是我只是想看看它是如何实现的。即如何调用子函数并传递值
const LeftIcon = ({ onDrawerToggle }) => (
<OnScreenResize debounce={50} bounds={[400,500]}>
{({ width, height }) =>
width > smallTablet.value
? Component(onDrawerToggle)
: OtherComponent()}
</OnScreenResize>
)
我不熟悉 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})
}
这是 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 });
}
}