reactJs组件的实例来呈现组件

Instance of reactJs component to render a component

本文关键字:组件 实例 reactJs      更新时间:2023-09-26

我可以使用一个reactJS组件的实例来呈现一个组件吗?例如,假设我的reactJS组件是

class myComponent extends Component{
  constructor(props){
    super(props)
    this.state = {
      next:false
    }
    this.alertSomething = this.alertSomething.bind(this);
    this.showNext = this.showNext.bind(this);
  }
  showNext(){
    console.log('wow');
    console.log(this.state, this, this.state.next);
    this.setState({next:true});
  }
  alertSomething(){
    alert('Alert Something')
    console.log(this.state, this, this.state.next);
    this.setState({next:true});
  }
  render(){
    return(
      <div className='column'>
      </div>
    )
  }
}
export default myComponent

现在,在我的另一个组件中,我可以做;

    let x = new displayContent.renderComponent();
    render(
     <x />
     //or
     <x.render />
    )

//我试了两种方法,它没有工作,我想一定有一些其他的方法来实现这一点,毕竟每个组件只是一个javascript对象。

同时,我可以调用函数来改变它的状态。喜欢。

x.someFunction();

其中someFunctino在反应组分中,做setState

有可能吗?还是我错过了什么?

编辑:我清楚地明白,当你想渲染一个反应组件,你总是可以做,<component />。这个问题只是出于好奇,这能做到吗?如果不是,为什么?我的意思是它和其他javascript对象有什么不同

那么,您可以使用React.createElement方法来呈现组件:

React.createElement(Component, params)

但是对于JSX,这是相同的:

<Component />

参考React文档中的多个组件

这不是你应该如何使用React。你不必处理对象实例化;React为你做这件事。用合成代替。

render() {
  return (
    <myComponent />
  )
}

同样,如果你想从父组件中设置子组件的状态,你可能应该移动父组件中的逻辑。

也许你正在寻找这样的东西。

import React, { Component } from "react";
import CamCapture from './CamCapture.js';
export default class ProctorVideoFeed extends Component{
constructor(props) {
    super(props);
    
    this.Camera = React.createElement(CamCapture);
    
    }
    //this.handleVideoClick = this.handleVideoClick.bind(this);

render(){
    return(
        <div>
            <span>{this.Camera}</span>
            <button onClick = {this.Camera.StopRecording}>Stop</button>
        </div>
    )
}

}

这里StopRecording是在CamCapture类中定义的函数。