为什么有人想在 React js 中将一个函数变成 class
Why would someone want to turn a function into a class in react js
我刚开始从官方网站学习 React js,在教程中有这一步,为了制作一个工作时钟,您将一个函数变成 class。我的问题是,既然可以用更简单的方法来完成,为什么有人要这样做呢?
如果您想访问所有 React.Component
功能,例如 props
和 state
、life cycle methods, ref
and much more,您需要 extend
来自 React.Component
.
您只能使用 class
(在 ES6
)
编辑
Just one thing, you can access to props too declaring a function
实际上这不是真的,无状态组件只是 returns jsx
的功能。它们是接受参数的正常、常规函数。
我们有时使用 props
关键字作为参数,只是作为一种习惯或惯例,但您可以使用任何您想要的关键字。
示例:
const MyHeader = (myParams) => (
// no props here
<h2>{myParams.value}</h2>
);
class MyApp extends React.Component{
render(){
const {message} = this.props; // i get access to this.props as i extended React.Component
return(<MyHeader value={message} />);
}
}
ReactDOM.render(<MyApp message="Hello!" />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
我刚开始从官方网站学习 React js,在教程中有这一步,为了制作一个工作时钟,您将一个函数变成 class。我的问题是,既然可以用更简单的方法来完成,为什么有人要这样做呢?
如果您想访问所有 React.Component
功能,例如 props
和 state
、life cycle methods, ref
and much more,您需要 extend
来自 React.Component
.
您只能使用 class
(在 ES6
)
编辑
Just one thing, you can access to props too declaring a function
实际上这不是真的,无状态组件只是 returns jsx
的功能。它们是接受参数的正常、常规函数。
我们有时使用 props
关键字作为参数,只是作为一种习惯或惯例,但您可以使用任何您想要的关键字。
示例:
const MyHeader = (myParams) => (
// no props here
<h2>{myParams.value}</h2>
);
class MyApp extends React.Component{
render(){
const {message} = this.props; // i get access to this.props as i extended React.Component
return(<MyHeader value={message} />);
}
}
ReactDOM.render(<MyApp message="Hello!" />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>