在ReactJS项目中使用多个ReactDOM.render()有什么问题吗?
我们正在进行一个Laravel项目,它完全是用JavaScript/HTML/JQuery编写的。我们正在考虑迁移,以便在Laravel支持的情况下做出反应。在最初的步骤中有许多ReactDOM.render()(每个组件),这样我们就可以在长期内逐步完全转换我们的代码库了吗 是否有必要访问在ReactJS项目中使用多个ReactDOM.render()有什么问题吗?,reactjs,Reactjs,我们正在进行一个Laravel项目,它完全是用JavaScript/HTML/JQuery编写的。我们正在考虑迁移,以便在Laravel支持的情况下做出反应。在最初的步骤中有许多ReactDOM.render()(每个组件),这样我们就可以在长期内逐步完全转换我们的代码库了吗 是否有必要访问ref,或者我们可以这样渲染每个组件: function Example() { // Declare a new state variable, which we'll call "count" c
ref
,或者我们可以这样渲染每个组件:
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(<App/>, document.querySelector("#form"))
函数示例(){
//声明一个新的状态变量,我们称之为“count”
const[count,setCount]=useState(0);
返回(
您单击了{count}次
设置计数(计数+1)}>
点击我
);
}
ReactDOM.render(,document.querySelector(“#form”))
对每个组件都这样使用:
// some html code and then
...
<div id="form"> </div>
<div id="modal"> </div>
<div id="navbar"> </div>
...
// rest of html code
//一些html代码,然后
...
...
//html代码的其余部分
是的,完全可以。React是为逐渐采用而设计的。是的,当您调用ReactDOM.render
多次时,它基本上只会触发一个diffing,非常类似于类组件的render
方法。事实上,我写了一篇文章(带教程),正好谈到了这个话题 这种方法的底线是,您可以使用widget/mini app的
mount
和unmount
功能公开全局对象,并在其内部调用ReactDOM.render
或ReactDOM.unmountComponentAtNode
window.MyComponent = {
mount: (props, container) => {
ReactDOM.render(<Component {...props} />, container);
},
unmount: (container) => {
ReactDOM.unmountComponentAtNode(container);
}
}
希望能有所帮助。谢谢,我刚刚详细阐述了我的评论,所以我把自己打造成水晶clear@RaminJafary好的,这符合你的需要吗?你解释的方式太棒了。这个项目是巨大的,将React挂接到项目中,我想我们可能没有这样的优势:拥有一个根元素,然后在同一个根DOM树中呈现其他组件(正如我在你的文章中所理解的那样,我想!)。因此,在项目转换为完全SPA之前,为每个组件使用多个单独的容器可以吗。这样的工作流是否会影响性能?这正是我的观点。您可以在自己的应用程序(根)中包装每个部分
class MyComponentWrapper extends PureComponent {
// create a ref so we can pass the element to mount and unmount
myRef = React.createRef();
componentDidMount() {
// initial render with props
window.MyComponent.mount(this.props, this.myRef.current);
}
componentDidUpdate(prevProps) {
if(prevProps !== this.props){
window.MyComponent.mount(this.props, this.myRef.current);
}
}
componentWillUnmount(){
window.MyComponent.unmount(this.myRef.current);
}
render() {
return <div ref={this.myRef}></div>
}
}