gpt4 book ai didi

javascript - React – 向其子组件公开组件函数

转载 作者:行者123 更新时间:2023-12-03 06:21:11 26 4
gpt4 key购买 nike

所以我试图为我将在网站上重复使用的不同部分创建一种抽象的“框架”。

所以现在我正在研究一个模态,它包括:

  • 标题
  • 内容
  • 操作(取消、保存等按钮)

我想怎么写:

<Modal> // <- This wrapper contains different functions for controlling the entire modal.
<ModalTitle>Editing</ModalTitle>
<ModalContent>
<form>
<input type="text"/>
</form>
</ModalContent>
<ModalActions/> // <- This one is empty since I already have save buttons as a default for it.
</Modal>

这将允许我更改内容、标题并为每个模式添加特定操作,以下是不同部分的一些代码:

var Modal = React.createClass({
close: function() {
this.props.onUserClose();
},
save: function() {
// validates inputs from a form, sends it back, and closes the modal
},
render: function() {
return (
<dialog className="mdl-dialog" ref="modal">
<button
type="button"
className="mdl-button mdl-js-button mdl-button--icon helper-modal-button--close"
onClick={this.close}
>
<i className="material-icons">clear</i>
</button>
{this.props.children}
</dialog>
);
}
};

标题非常简单,但这抽象了类名,如果需要的话,可以让我在里面添加不同的东西。

var ModalTitle = React.createClass({
render: function() {
return (
<h2 className="mdl-dialog__title">{this.props.children}</h2>
);
}
});

内容与标题几乎相同。

var ModalContent = React.createClass({
render: function() {
return (
<div className="mdl-dialog__content">
<form id="modal-form">{this.props.children}</form>
</div>
);
}
});

现在我要采取行动,以及我需要帮助的地方:

var ModalActions = React.createClass({
render: function() {
return (
<div className="mdl-dialog__actions">
<button type="button" className="mdl-button" onClick={this.save}>Save</button>
{this.props.children}
</div>
);
}
});

现在,如您所见,我已经为操作添加了保存操作,因为我想在每个模式上都使用它,但问题是如何访问 的保存功能?我不认为我能够将它作为来自父级的 Prop 传递,并且我想必须拦截它的子级,检查并给它一个保存功能的 Prop ,但我找不到任何好的信息如何正确地做到这一点,而不是如何确定哪个子级是操作者。

我认为效果最好的另一种方法是,我可以将保存功能公开给所有 child ,并且仅在保存操作时对其进行操作。这还允许我编写利用“API”的自定义操作。

仍然没有找到任何关于如何做到这一点的好信息,有什么想法吗?

最佳答案

您可以使用React.Children迭代子元素,然后使用 React.cloneElement 使用新的 props 克隆每个元素(浅合并)

render: function() {
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
doSomething: this.doSomething
})
);

return <div>{childrenWithProps}</div>
}

关于javascript - React – 向其子组件公开组件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38866539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com