1.定义组件最简单的方式就是编写 JavaScript 函数:
function Welcome(props) {
return <h1>Hello, {props.name}h1>;
}
该函数是一个有效的 React 组件,因为它接收唯一带有数据的 “props”(代表属性)对象与并返回一个 React 元素。这类组件被称为“函数组件”,因为它本质上就是 JavaScript 函数。
2.你同时还可以使用 ES6 的 class 来定义组件:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}h1>;
}
}
1.之前,我们遇到的 React 元素都只是 DOM 标签:
const element = ;
2.不过,React 元素也可以是用户自定义的组件:
const element =
3.当 React 元素为用户自定义组件时,它会将 JSX 所接收的属性(attributes)以及子组件(children)转换为单个对象传递给组件,这个对象被称之为 “props”。
例如,这段代码会在页面上渲染 “Hello, Sara”:
function Welcome(props) {
return <h1>Hello, {props.name}h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
分析:
组件名称必须以大写字母开头
react会将小写字母开头的组件视为原生dom标签
组件可以在其输出中引用其他组件。
这就可以让我们用同一组件来抽象出任意层次的细节。
按钮,表单,对话框,甚至整个屏幕的内容:在 React 应用程序中,这些通常都会以组件的形式表示。
function Welcome(props) {
return <h1>Hello, {props.name}h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
将组件拆分为更小的组件。
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
div>
div>
<div className="Comment-text">
{props.text}
div>
<div className="Comment-date">
{formatDate(props.date)}
div>
div>
);
}
可以拆分为Avatar组件
function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}
UserInfo组件
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
div>
div>
);
}
Comment组件
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
div>
<div className="Comment-date">
{formatDate(props.date)}
div>
div>
);
}
组件无论是使用函数声明还是通过 class 声明,都决不能修改自身的 props。