gpt4 book ai didi

reactjs - React render props 是否会导致子组件的重新安装?

转载 作者:行者123 更新时间:2023-12-03 14:13:06 25 4
gpt4 key购买 nike

我只是想知道人们是否知道使用“渲染 Prop ”模式是否会导致子组件的过度安装/卸载。例如,改编自 React 文档 ( https://reactjs.org/docs/render-props.html ):

<Mouse>
{mouse => (
<ShowMousePosition mouse={mouse}/>
)}
</Mouse>


class ShowMousePosition extends React.Component {
componentDidMount(){
console.log('mounting!')
}
render () {
const {mouse} = this.props
return (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)
}
}

我知道 react 文档说:

Using a render prop can negate the advantage that comes from using React.PureComponent if you create the function inside a render method. This is because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop.

但是,会“安装!”当用户移动鼠标时被一遍又一遍地调用?

谢谢!

最佳答案

我继续尝试用 fiddle 回答我自己的问题。看来“正在装!”不会被一遍又一遍地调用:

https://jsfiddle.net/69z2wepo/186690/

代码如下:

class Hello extends React.Component {
render() {
return <Mouse>
{mouse => (
<ShowMousePosition mouse={mouse}/>
)}
</Mouse>
}
}

class Mouse extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}

handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}

render() {
return (
<div style={{ height: 800, width: 800 }} onMouseMove={this.handleMouseMove}>

{/*
Instead of providing a static representation of what <Mouse> renders,
use the `render` prop to dynamically determine what to render.
*/}
{this.props.children(this.state)}
</div>
);
}
}




class ShowMousePosition extends React.Component {
componentDidMount(){
console.log('mountin!')
}
render () {
const {mouse} = this.props
return (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)
}
}

ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);

关于reactjs - React render props 是否会导致子组件的重新安装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50729880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com