可以使用以下语法在 React 中创建组件:
import React, { Component } from 'react';
import ChildComponentOne from './ChildComponentOne';
import ChildComponentTwo from './ChildComponentTwo';
class App extends Component {
constructor(props) {
super(props);
this.state = {
propOne : '',
propTwo : '',
propThree : '',
};
this.doThis = this.doThis.bind(this);
this.doThat = this.doThat.bind(this);
}
doThis() {
...doingThis code
}
doThat() {
...doingThat code
}
render() {
return (
<ChildComponentOne propOne={this.state.propOne} doThis={this.doThis}/>
<ChildComponentTwo propTwo={this.state.propTwo} propThree={this.state.propThree} doThat={this.doThat}/>
);
}
}
export default App;
React 是否利用这个 class语法,因为他们试图为组织组件制作一个封装和整洁的符号。构造方法之后的所有其他内容都以 React 为中心。
或者可以这样写:
App.prototype.doThis = function(){};
App.prototype.doThat = function(){};
function App(){
this.state = {
propOne : '',
propTwo : '',
propThree : '',
};
componentDidMount(){...somecode..}
componentWillUnmount(){...somecode..}
render(){
return (
<ChildComponentOne propOne={this.state.propOne} doThis={this.doThis}/>
<ChildComponentTwo propTwo={this.state.propTwo} propThree={this.state.propThree} doThat={this.doThat}/>
);
}
}
我知道我离得不远,因为可以只利用一个常规函数来创建所谓的功能组件
。
猜猜问题是如何利用生命周期方法...
最佳答案
ES6 类是函数类的语法糖。当应用程序被转换为 ES5 时,它们实际上变成了函数。
React 类组件应该有 render
方法,并且原型(prototype)继承自 React.Component
,这就是它们与函数式组件的不同之处。
render
最好是原型(prototype)方法:
App.prototype = Object.create(Component.prototype);
App.prototype.render = function () { ... };
function App(props) { ... }
因为 this.render = ...
实例方法不合理。也有可能被一些第三方库认为是原型(prototype)方法。
关于javascript - React 组件中的不同区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53786399/