【发布时间】:2021-03-06 12:07:05
【问题描述】:
我正在使用 React 库创建一个应用程序,但我的问题更多与 JavaScript ES6 本身有关。
- 我有一个组件(页面),我在其中使用了我自己设计的 FAB(浮动操作按钮):
class Page extends Component {
.
.
.
render() {
return (<>
.
.
.
<FloatingActionButton
mainActionContent={<Icon.Plus size="48" />}
onClick={() => {
this.setState({
examinationData: null,
modalExamination: true,
});
}}
dropdown={myFAB}
/>
.
.
.
</>)
}
}
- 在主组件中,我将 FAB 配置存储在一个常量中
class Page extends Component {
.
.
.
doRefreshList() {...}
doDeleteSelected() {...}
.
.
.
render() {
const myFAB = {
trigger: {
className: "m-0 rounded-circle noCaret badge-overlay",
style: { paddingLeft: "5em", paddingRight: ".5em", zIndex: 0 },
content: (
<React.Fragment>
<Icon.ThreeDotsVertical size="24" />
{this.state.selected.length > 0 && (
<Badge pill variant="danger">
{this.state.selected.length}
</Badge>
)}
</React.Fragment>
),
},
header: "Akcje",
items: [
{
text: "Odśwież widok",
icon: <Icon.ArrowRepeat size="16" />,
onClick: () => {
this.doRefreshList();
},
},
{},
{
text: "Zaznacz wszystkie",
icon: <Icon.SquareFill size="16" />,
onClick: null, // <-- is `null` because it is not implemented yet
},
{
text: "Odznacz wszystkie",
icon: <Icon.Square size="16" />,
onClick: null,
},
{
text: "Odwróć zaznaczenie",
icon: <Icon.SquareHalf size="16" />,
onClick: null,
},
{},
{
className: "d-flex flex-row justify-content-between align-items-center",
disabled: this.state.selected.length === 0,
text: (
<React.Fragment>
<span>
<Icon.Trash size="16" /> Usuń zaznaczone
</span>
{this.state.selected.length > 0 && (
<Badge pill variant="danger">
{this.state.selected.length}
</Badge>
)}
</React.Fragment>
),
onClick: this.doDeleteSelected,
},
{},
{
text: "Ustawienia widoku...",
icon: <Icon.Sliders size="16" />,
onClick: () => {
this.setState({ modalViewOption: true });
},
},
],
};
return (
.
.
.
)
}
}
- 但是,如你所见,在这个常量中,我调用了主组件(页面)的方法和状态
这还不错,因为它运行良好,但我不喜欢代码的视觉效果。我想分离 FAB 配置 - 将其放在不同的文件中 - 并将其导入页面组件。 我就是不能这样:
import FABConfig from 'path/to/file';
class Page extends Component {
.
.
.
render() {
.
.
.
return (
.
.
.
<FloatingActionButton
mainActionContent={<Icon.Plus size="48" />}
onClick={() => {
this.setState({
examinationData: null,
modalExamination: true,
});
}}
dropdown={FABConfig}
/>
)
}
}
当然,它会导入,但会崩溃 - 不知道 this 是什么。
我怎样才能对组件配置进行这样的“导入”,而不会在代码中造成太多混乱:D?
【问题讨论】:
-
我在元素的正确嵌套方面稍微更正了问题中的代码 - 它是关于查看位于何处的内容。
标签: javascript reactjs node-modules es6-modules