[英]Instance of reactJs component to render a component
我可以使用 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 类中定义的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.