花了一些时间学习React后,我理解了创建组件的两个主要范例之间的区别
我的问题是我什么时候应该使用哪一个?为什么?一个在另一个上有什么好处/权衡?
ES6/7课程:
import React, { Component } from 'react';
export class MyComponent extends Component {
render() {
return (
<div></div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
功能:
const MyComponent = (props) => {
return (
<div></div>
);
}
Run Code Online (Sandbox Code Playgroud)
只要没有任何状态可以被该组件操纵,我就会想到功能......但是这样吗?
我猜我是否使用任何生命周期方法,最好使用基于类的组件.
官方 ReactJs 文档建议按照点符号创建组件,如React-bootstrap库:
<Card>
<Card.Body>
<Card.Title>Card Title</Card.Title>
<Card.Text>
Some quick example text to build on the card title and make up the bulk of
the card's content.
</Card.Text>
</Card.Body>
</Card>
Run Code Online (Sandbox Code Playgroud)
感谢这个问题,我知道我可以使用功能组件来创建这个结构,就像在 javascript 中一样:
const Card = ({ children }) => <>{children}</>
const Body = () => <>Body</>
Card.Body = Body
export default Card
Run Code Online (Sandbox Code Playgroud)
使用 TypeScript,我决定向其中添加相应的类型:
const Card: React.FunctionComponent = ({ children }): JSX.Element => <>{children}</>
const Body: React.FunctionComponent = (): JSX.Element => <>Body</>
Card.Body …Run Code Online (Sandbox Code Playgroud) 我有一个简单的组件,它应该在我的表单组件中呈现不同类型的字段:
import React from "react";
export default class Field extends React.Component {
render() {
switch (this.props.type) {
case 'textarea': {
return (
<div className="col-xs-12">
<textarea
placeholder={this.props.placeholder}
name={this.props.name}
>
</textarea>
</div>
)
}
case 'text': {
return (
<div className="col-md-6 col-lg-4">
<input
type="text"
placeholder={this.props.placeholder}
name={this.props.name}
/>
</div>
)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的表单组件中使用此组件,如下所示:
export default class SubmitForm extends React.Component {
render() {
return (
.
.
.
<Field
type="text"
placeholder="something"
name="something"
/>
<Field
type="textarea"
placeholder="another"
name="othername"
/>
.
.
.
) …Run Code Online (Sandbox Code Playgroud)