在 ReactJS 中动态导入组件
Dynamically importing components in ReactJS
我刚刚开始接触 react-js,遇到了这段代码,用于在我的应用程序中动态导入组件,但我似乎无法理解?
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Dynamic extends Component {
constructor(props) {
super(props);
this.state = { module: null };
}
componentDidMount() {
const { path } = this.props;
import(`${path}`)
.then(module => this.setState({ module: module.default }))
}
render() {
const { module: Component } = this.state; // Assigning to new variable names @see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
return(
<div>
{Component && <Component />} // the code i can't figure out
//{Component} works fine too
//{<Component />} gives error
</div>
)
}
}
ReactDOM.render(<Dynamic path='./FirstComponent' />, document.getElementById('root'));
谁能解释一下我突出显示的代码行,它在我看来是某种条件渲染,但据我所知,它的工作原理就像左手评估为真时右手被渲染一样,但为什么此代码也仅适用于 {Component} 吗?
因为在初始渲染时 {Component}
评估为 null。
因为你已经使用了解构。
const { module: Component } = this.state;
所以
Component = null
但是当您在初始渲染时使用 <Component/>
时,没有 <Component/>
组件。所以使用 { <Component />}
会出错。
使用Component
和<Component/>
是不同的。
我刚刚开始接触 react-js,遇到了这段代码,用于在我的应用程序中动态导入组件,但我似乎无法理解?
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class Dynamic extends Component {
constructor(props) {
super(props);
this.state = { module: null };
}
componentDidMount() {
const { path } = this.props;
import(`${path}`)
.then(module => this.setState({ module: module.default }))
}
render() {
const { module: Component } = this.state; // Assigning to new variable names @see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
return(
<div>
{Component && <Component />} // the code i can't figure out
//{Component} works fine too
//{<Component />} gives error
</div>
)
}
}
ReactDOM.render(<Dynamic path='./FirstComponent' />, document.getElementById('root'));
谁能解释一下我突出显示的代码行,它在我看来是某种条件渲染,但据我所知,它的工作原理就像左手评估为真时右手被渲染一样,但为什么此代码也仅适用于 {Component} 吗?
因为在初始渲染时 {Component}
评估为 null。
因为你已经使用了解构。
const { module: Component } = this.state;
所以
Component = null
但是当您在初始渲染时使用 <Component/>
时,没有 <Component/>
组件。所以使用 { <Component />}
会出错。
使用Component
和<Component/>
是不同的。