[英]React Function vs Template re-render
I have simple counter app 我有简单的柜台应用
import * as ReactDOM from 'react-dom';
import * as React from 'react';
const app = document.querySelector('#root');
let count = 0;
const increment = () => {
count++;
render();
}
var as = {};
const render = () => {
var Component = () => (
<div>
<h2>Differ</h2>
<h1>123{count}</h1>
<button onClick={increment}>+</button>
<div>3333</div>
</div>
);
var template = (
<div>
<h2>Differ</h2>
<h1>123{count}</h1>
<button onClick={increment}>+</button>
<div>3333</div>
</div>
);
// If click on increment react re-render only the count "text" element
ReactDOM.render(
template, app
);
// If click on increment react re-render the whole component
// ReactDOM.render(
// <Component />, app
// );
}
render();
if i use ReactDOM.render(template, app)
. 如果我使用ReactDOM.render(template, app)
。 react re-render only the specific element. react仅重新渲染特定元素。
if i use ReactDOM.render(<Component/>, app)
react re-render whole app. 如果我使用ReactDOM.render(<Component/>, app)
react重新渲染整个应用程序。
they are same components so why it act like this ? 它们是相同的组件,为什么要这样运行? what the different between Component vs template ? Component vs template有什么区别?
If I declare Componenet example outside render function react render only the spesific element 如果我在渲染函数外部声明Componenet示例,则仅渲染spesific元素
i check this with chrome dev-tools( rendering => paint flushing). 我用chrome dev-tools(渲染=>油漆冲洗)检查了一下。
Ideally you shouldn't be re-rendering the whole tree every time, anyways. 理想情况下,无论如何, 您不应该每次都重新渲染整个树。 You should be using "internal" state 您应该使用“内部”状态
class Component extends React.Component {
state = { count: 0 }
render() {
const onClick = () => { this.setState(({ count }) => ({ count: count + 1 }))}
return (
<button>{this.state.count}</button>
)
}
}
The difference between template
and Component
is that template
is a JSX/React Element, and Component
is a React (Stateless/Functional)Component. template
和Component
之间的区别在于, template
是JSX / React元素,而Component
是React(无状态/功能)组件。
See here for a little more info 看到这里更多信息
React will also try to resolve and optimise the difference between two trees (old/new). React也将尝试解决和优化两棵树(旧/新)之间的差异。
In the first example, render(template, app)
- you're still using the same template
element, so React will compare its children against the new children, and update only those whose props have changed. 在第一个示例中, render(template, app)
-您仍在使用相同的template
元素,因此React会将其子代与新的子代进行比较,并仅更新其道具已更改的子代。 In the second example, you're passing in a new instance of Component
( <Component/>
is syntactic sugar for React.createElement("Component")
), so React will completely replace that subtree. 在第二个示例中,您传入了Component
的新实例( <Component/>
是React.createElement("Component")
语法糖),因此React将完全替换该子树。
Here's some info on how React reconciles between tree-states. 这是一些关于React如何在树状态之间协调的信息 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.