我将发布您的实际代码:
class Application extends React.Component {
render() {
return (
<div>
{/*
Clicking this component only logs
the parents render function
*/}
<DynamicParent>
<Child />
</DynamicParent>
{/*
Clicking this component logs both the
parents and child render functions
*/}
<StaticParent />
</div>
);
}
}
class DynamicParent extends React.Component {
state = { x: false };
render() {
console.log("DynamicParent");
return (
<div onClick={() => this.setState({ x: !this.state.x })}>
{this.props.children}
</div>
);
}
}
class StaticParent extends React.Component {
state = { x: false };
render() {
console.log("StaticParent");
return (
<div onClick={() => this.setState({ x: !this.state.x })}>
<Child />
</div>
);
}
}
function Child(props) {
console.log("child");
return <div>Child Text</div>;
}
在应用程序渲染中编写此代码时:
<StaticParent />
呈现的是:
<div onClick={() => this.setState({ x: !this.state.x })}>
<Child />
</div>
实际上,发生的(大致)是这样的:
function StaticParent(props) {
return React.createElement(
"div",
{ onClick: () => this.setState({ x: !this.state.x }) },
React.createElement(Child, null)
);
}
React.createElement(StaticParent, null);
当你像这样渲染你的动态租金时:
<DynamicParent>
<Child />
</DynamicParent>
这就是实际发生的情况(同样,粗略地说)
function DynamicParent(props) {
return React.createElement(
"div",
{
onClick: () => this.setState({ x: !this.state.x }),
children: props.children
}
);
}
React.createElement(
DynamicParent,
{ children: React.createElement(Child, null) },
);
这就是两种情况下的子元素:
function Child(props) {
return React.createElement("div", props, "Child Text");
}
这是什么意思?在StaticParent组件中,每次调用StaticParent的render方法时都会调用React.createElement(Child, null)
.在DynamicParent case 中,子对象被创建一次并作为props 传递.因为React.createElement
是一个纯函数,所以它可能会被存储在某个地方以提高性能.
在DynamicParent case 中,让子元素的渲染再次运行的是子元素props 的变化.例如,如果父对象的状态用作子对象的props ,则在这两种情况下都会触发重新渲染.
我真的希望丹·阿布拉莫夫不要出现在 comments 中,把这个答案说成垃圾,写起来很痛苦(但很有趣)