![](/img/trans.png)
[英]Why is the internal implementation of React.Component a function and not an ES6 class?
[英]Call method on ES6 class instance of React.Component
我是React的新手,我将它与ES6类结合使用。 我有一个继承自React.Component
的类,并根据其state
的单个属性呈现DOM。 这是看起来如何:
class LoadingScreen extends React.Component {
constructor(props) {
super(props);
this.state = { state: 'isHidden' };
showTrying() {
this.setState({ state: 'isTrying' });
}
hideAll() {
this.setState({ state: 'isHidden' });
}
render() {
switch (this.state.state) {
case 'isHidden':
return null;
case 'isTrying':
// Returns a bunch of DOM elements
}
}
在父类中,这不是React组件(我试图迁移不使用框架的现有代码),我想:
LoadingScreen
的实例 React.render
将其插入DOM中 hide
或showTrying
等方法来更新其状态 我试过了:
this.loadingScreen = new LoadingScreen();
React.render(this.loadingScreen, mountNode); // React invalid component error
// Later on...
this.loadingScreen.showTrying();
并尝试过:
this.loadingScreen = React.render(React.createElement("LoadingScreen"), mountNode);
// Later on...
this.loadingScreen.showTrying(); // Undefined is not a function
显然我在这里缺少一些基本的东西。 :)
更常见的是,您在LoadingScreen
组件实例上设置属性以控制内部表示的可见性,而不是通过对象实例上的函数调用来调整状态。
class LoadingScreen extends React.Component {
constructor(props) {
super(props);
}
render() {
switch (this.props.mode) {
case 'isHidden':
return null;
case 'isTrying':
// Returns a bunch of DOM elements
}
}
}
LoadingScreen.propTypes = {
mode: React.PropTypes.string
};
LoadingScreen.defaultProps = {
mode: 'isTrying'
};
然后,从父母那里,你会做这样的事情,例如:
var currentMode = "isTrying";
React.render(<LoadingScreen mode={ currentMode } />, mountNode);
或者,另一种模式是父容器/组件使用属性的值(我称之为mode
),根本不创建和渲染LoadingScreen
组件。
如果需要LoadingScreen
,您可以将property
值复制到本地状态。
你的第二种方法很接近。
React.createElement
的第一个参数可以是字符串(div,span等)或React.Component
的子类。 在您的情况下,第一个参数应该是LoadingScreen
。
this.loadingScreen = React.render(React.createElement(LoadingScreen), mountNode);
this.loadingScreen.showTrying();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.