我想用处理相同任务的 React 组件替换 javascript 的内置 alert()
函数:即,向用户显示快速、可忽略的消息。
现在,我可以通过创建一个组件并将其放入我的标记中来实现这一点。例如
<div>
<BunchOfComponents />
<MoreComponents />
<MyAlertDialog open={this.props.shouldShowAlert} />
</div>
然后通过 Redex 或其他方式控制其 open
状态使其显示。
但是,我喜欢做的是,它能够不在我的标记中声明它,而是注入(inject)到dom 通过一个函数。
有点像...
myCoolFunction() {
const alert = (
<MyAlert
open={true}
msg="Hello World"
/>
)
DOM.findNode('someID').insert(alert); <-- fake API obviously
}
是否可以像这样动态附加组件?
最佳答案
这是我在工作中做的肮脏方式(听起来不对...) http://codepen.io/matthsiung/pen/JKOpVW
我确信有更好的“正确”方法来做到这一点,但它会自行清理,所以它对我有用。
这里是关键点:
对话触发器
//Your trigger function will render the dialog component to a newly created dummy div,
// while also passing it into the component as a prop
function showDialog() {
var div = document.createElement('div');
ReactDOM.render(
<Dialog container={div}/>,
document.body.appendChild(div)
);
}
对话框组件:
//When your dialog component closes it unmounts itself
close(){
ReactDOM.unmountComponentAtNode(this.props.container);
},
//Before unmount it cleans up after itself by removing the dummy div
componentWillUnmount() {
document.body.removeChild(this.props.container);
},
关于javascript - 你如何动态地将 React 组件插入 DOM(例如对话框)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38341129/