关于React组件
React的组件有函数和类两种
函数组件
接收一个叫做props(属性的意思)的对象作为参数,并返回一个React元素。
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件 zǔ
实施构造函数并需要调用super(props)。在render()方法中访问和使用在构造函数中定义的props。
class Welcome extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件的渲染
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;
root.render(element);
-
- 以要素作为参数执行root.render()。
-
- React调用Welcome组件时,传递props作为{name: ‘Sara’}。
-
- Welcome组件返回一个h1元素作为输出。
- ReactDOM将DOM重写以匹配返回的h1元素。
组合组件
组件可以引用其他组件。这样一来,就能够重复使用组件(使用相同的组件多次)。
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}