从元素中生成组件

React making components out of elements

本文关键字:组件 元素      更新时间:2023-09-26

我目前正在把我的网站的元素放在一起,但做出反应的组件出来。这里有一个按钮,例如:

import React       from 'react';
class Button extends React.Component {
  render() {
    return <button className={this.props.bStyle}>{this.props.title}</button>;
  }
}
export default Button;

我还有很多其他的元素要放到react组件中,所以会有一个很大的列表。

问题是,如果你有很多,你需要导入所有的列表,可能会变得太大。

想象50个这样的东西:

import Element from './Element.component'; // x50 ?
我的问题是……它们是在React中导入大型组件列表的更好方法吗?

您可以将所有元素导入到一个文件中,并单独导出所有元素。然后你就可以导入所有的as元素,并使用as elements. somecomponent。

// common.js because you ll commonly use them
import Element from './Element.component'; 
import Element2 from './Element.component2'; // x50 ?
/* ... */
export { Element, Element2 /* ... */ };
// in someOtherFile.js
import * as Elements from './common';
/* 
   now you are able to use these common elements as 
   <Elements.Element /> 
   <Elements.Element2 />
   ... 
*/