反应 - 如何实例化组件以及它们何时相同?
react - how to instantiate a component and when are they identical?
我对以下代码有一些疑问。
据我了解,Example
是一个 class,它在作为参数传递给 ReactDOM.render
时首先被实例化。
渲染时,它首先调用 componentWillMount
方法。
我不明白的是第二个ReactDOM.render
调用。
第二个ReactDom.render
调用中的<Example />
是否与第一个相同。
我以为第二次调用实例化了 Example 的第二个实例,但显然不是,因为 componentWillMount
方法没有被调用。
为什么两个<Example />
是同一个实例?如何创建 <Example />
的 second/separate 实例?
import React from 'react';
import ReactDOM from 'react-dom';
export class Example extends React.Component {
componentWillMount() {
alert('component is about to mount!');
}
render() {
return <h1>Hello world</h1>;
}
}
ReactDOM.render(
<Example />,
document.getElementById('app')
);
setTimeout(() => {
ReactDOM.render(
<Example />,
document.getElementById('app')
);
}, 2000);
如果您想要两个实例,那么您应该有两个具有不同 ID 的主 div:
import React from 'react';
import ReactDOM from 'react-dom';
export class Example extends React.Component {
componentWillMount() {
alert('component is about to mount!');
}
render() {
return <h1>Hello world</h1>;
}
}
ReactDOM.render(
<Example />,
document.getElementById('app')
);
ReactDOM.render(
<Example />,
document.getElementById('appTwo')
);
并且在 HTML 中:
<div id="app"></div>
<div id="appTwo"></div>
我对以下代码有一些疑问。
据我了解,Example
是一个 class,它在作为参数传递给 ReactDOM.render
时首先被实例化。
渲染时,它首先调用 componentWillMount
方法。
我不明白的是第二个ReactDOM.render
调用。
第二个ReactDom.render
调用中的<Example />
是否与第一个相同。
我以为第二次调用实例化了 Example 的第二个实例,但显然不是,因为 componentWillMount
方法没有被调用。
为什么两个<Example />
是同一个实例?如何创建 <Example />
的 second/separate 实例?
import React from 'react';
import ReactDOM from 'react-dom';
export class Example extends React.Component {
componentWillMount() {
alert('component is about to mount!');
}
render() {
return <h1>Hello world</h1>;
}
}
ReactDOM.render(
<Example />,
document.getElementById('app')
);
setTimeout(() => {
ReactDOM.render(
<Example />,
document.getElementById('app')
);
}, 2000);
如果您想要两个实例,那么您应该有两个具有不同 ID 的主 div:
import React from 'react';
import ReactDOM from 'react-dom';
export class Example extends React.Component {
componentWillMount() {
alert('component is about to mount!');
}
render() {
return <h1>Hello world</h1>;
}
}
ReactDOM.render(
<Example />,
document.getElementById('app')
);
ReactDOM.render(
<Example />,
document.getElementById('appTwo')
);
并且在 HTML 中:
<div id="app"></div>
<div id="appTwo"></div>