组件 & Props

函数组件与 class 组件#

函数组件#

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

class组件#

ES6语法
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
TypeScript语法
import { Component } from "react"
type HelpProp = {}
type HelpState = {
time: Date
}
export class Help extends Component<HelpProp, HelpState> {
timer: number
constructor(prop: HelpProp) {
super(prop);
this.state = {
time: new Date()
};
}
interval() {
this.timer = window.setInterval(() => {
this.setState({
time: new Date()
});
}, 1000);
}
componentDidMount() {
this.interval();
}
render() {
const { time } = this.state;
return (
<div>{time.toLocaleString()}</div>
);
}
componentWillUnmount() {
if (this.timer) {
clearInterval(this.timer);
}
}
}

渲染组件:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
note
  1. React 会将以小写字母开头的组件视为原生 DOM 标签。例如,<div /> 代表 HTML 的 div 标签,而 <Welcome /> 则代表一个组件,并且需在作用域内使用 Welcome
  2. 组件不应该修改props