我将React组件附加到已经存在的Web应用程序中的几个JQuery对话框中。我没有使用JQuery来操作DOM(除了最初添加到对话框中),而是让React处理所有事情,并且它正在按现在的方式工作。当状态改变时,对话框中的React组件也会改变。我想知道的是,由于React组件不再位于它最初呈现在的div中,因此这样做会有任何无法预料的问题吗?而且这会被视为不良做法吗?这是一些示例代码:
index.js
const createStoreWithMiddleWare = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={ createStoreWithMiddleWare(reducers) }>
<App/>
</Provider>,
document.getElementById('app')
);
应用程序组件
export default class App extends Component{
render() {
return(
<div>
<ChatWindow />
</div>
);
}
}
ChatWindow组件
class ChatWindow extends Component {
render() {
return (
<div id="ChatContainer">
<div className='ChatMenu' id="MainChat">
<UserList></UserList>
<ChatMessageView></ChatMessageView>
<UserInput></UserInput>
</div>
</div>
);
}
componentDidMount() {
this.createDialog();
}
createDialog(){
const dialogId = "chatDialog";
const _dialogId = `#${dialogId}`;
const chatDiv = `<div id="${dialogId}"></div>`;
$(chatDiv).dialog({
width: 650,
height: 625
});
$(_dialogId).dialog();
$('#ChatContainer').appendTo(_dialogId);
}
}
最佳答案
我怀疑React会强烈反对。最好先创建jQuery对话框(在外部),然后在其中渲染React组件。
var $chatDiv = $("<div class='dialog'>"); //create new element
$("body").append( $chatDiv ); //add it to page
$chatDiv.dialog({ //make a dialog
width: 650,
height: 625
});
ReactDOM.render( <ChatWindow />, $chatDiv[0] ); //render component inside