Reactjs学习记录(005)-组件&props

function Welcome(props) {
  return 

Hello, {props.name}

; } const element = ; ReactDOM.render( element, document.getElementById('root') );

当React遇到的元素是用户自定义的组件,它会将JSX属性作为单个对象传递给该组件,这个对象称之为“props”。

我们来回顾一下在这个例子中发生了什么:

  1. 我们对元素调用了ReactDOM.render()方法。
  2. React将{name: 'Sara'}作为props传入并调用Welcome组件。
  3. Welcome组件将

    Hello, Sara

    元素作为结果返回。
  4. React DOM将DOM更新为

    Hello, Sara


function Welcome(props) {
  return 

Hello, {props.name}

; } function App() { return ( {/*直接return();*/}
{/*在组件中嵌套组件*/}
); } ReactDOM.render( , document.getElementById('root') );

提取组件一开始看起来像是一项单调乏味的工作,但是在大型应用中,构建可复用的组件完全是值得的。当你的UI中有一部分重复使用了好几次(比如,ButtonPanelAvatar),或者其自身就足够复杂(比如,AppFeedStoryComment),类似这些都是抽象成一个可复用组件的绝佳选择,这也是一个比较好的做法。

function formatDate(date) {  //这里只是一个函数而非组件,首字母没有大写
  return date.toLocaleDateString();
}

function Avatar(props) {
  return (
    {props.user.name}
  );
}

function UserInfo(props) {
  return (
    
{props.user.name}
); } function Comment(props) { return (
{props.text}
{formatDate(props.date)}
); } const comment = { //这里是一个对象吗 date: new Date(), text: 'I hope you enjoy learning React!', author: { name: 'Hello Kitty', avatarUrl: 'http://placekitten.com/g/64/64' } }; ReactDOM.render( , document.getElementById('root') );

Props的只读性

无论是使用函数或是类来声明一个组件,它决不能修改它自己的props。来看这个sum函数:

function sum(a, b) {
  return a + b;
}

类似于上面的这种函数称为“纯函数”,它没有改变它自己的输入值,当传入的值相同时,总是会返回相同的结果。

与之相对的是非纯函数,它会改变它自身的输入值:

function withdraw(account, amount) {
  account.total -= amount;
}

React是非常灵活的,但它也有一个严格的规则:

所有的React组件必须像纯函数那样使用它们的props。

function tick() {    //这里只是定义了一个函数
  const element = (
    

Hello, world!

It is {new Date().toLocaleTimeString()}.

); ReactDOM.render( element, document.getElementById('root') ); } setInterval(tick, 1000); //注意这里的调用tick没有加()

下面封装了一个Clock组件

function Clock(props) {  //这里是组件
  return (
    

Hello, world!

It is {props.date.toLocaleTimeString()}.

); } function tick() { //这里是方法 ReactDOM.render( , document.getElementById('root') ); } setInterval(tick, 1000); //这里调用方法

然而,它错过了一个关键的要求:Clock设置一个定时器并且每秒更新UI应该是Clock的实现细节。

理想情况下,我们写一次 Clock 然后它能更新自身:

为了实现这个需求,我们需要为Clock组件添加状态

状态与属性十分相似,但是状态是私有的,完全受控于当前组件。

我们之前提到过,定义为类的组件有一些特性。局部状态就是如此:一个功能只适用于类。

class Clock extends React.Component {  //component{render()  {return ();}   }
  render() {
    return (
      

Hello, world!

It is {this.props.date.toLocaleTimeString()}.

{/*没有(props)而是变成了this.props*/}
); } } function tick() { ReactDOM.render( //在方法中引入组件,渲染节点 , //props从这里传入组件 document.getElementById('root') ); } setInterval(tick, 1000);


将函数转换为类

你可以通过5个步骤将函数组件 Clock 转换为类

  1. 创建一个名称扩展为 React.Component 的ES6 类

  2. 创建一个叫做render()的空方法

  3. 将函数体移动到 render() 方法中

  4. 在 render() 方法中,使用 this.props 替换 props

  5. 删除剩余的空函数声明


class Clock extends React.Component {  //component{render()  {return ();}   }
  render() {
    return (
      

Hello, world!

It is {this.props.date.toLocaleTimeString()}.

{/*没有(props)而是变成了this.props*/}
); } } function tick() { ReactDOM.render( //在方法中引入组件,渲染节点 , //props从这里传入组件 document.getElementById('root') ); } setInterval(tick, 1000);

为一个类添加局部状态

我们会通过3个步骤将 date 从属性移动到状态中:

class Clock extends React.Component {
  constructor(props) {
    super(props);  //注意我们如何传递 props 到基础构造函数的:
    this.state = {date: new Date()};  //step-two添加一个类构造函数来初始化状态 this.state
  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

{/*step-one在 render() 方法中使用 this.state.date 替代 this.props.date*/}
); } } ReactDOM.render( , //step-three从 元素移除 date 属性: document.getElementById('root') );

将生命周期方法添加到类中

在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。

每当Clock组件第一次加载到DOM中的时候,我们都想生成定时器,这在React中被称为挂载

同样,每当Clock生成的这个DOM被移除的时候,我们也会想要清除定时器,这在React中被称为卸载

我们可以在组件类上声明特殊的方法,当组件挂载或卸载时,来运行一些代码:



class Clock extends React.Component {
  constructor(props) {           //构造函数
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {  //当组件输出到 DOM 后会执行 componentDidMount() 钩子,这是一个建立定时器的好地方
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {  
    clearInterval(this.timerID); //在 componentWillUnmount()生命周期钩子中卸载计时器:
  }

  tick() {     //最后,我们实现了每秒钟执行的 tick() 方法。它将使用 this.setState() 来更新组件局部状态:
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } } ReactDOM.render( , document.getElementById('root') );

现在时钟每秒钟都会执行。

让我们快速回顾一下发生了什么以及调用方法的顺序:

  1. 当  被传递给 ReactDOM.render() 时,React 调用 Clock 组件的构造函数。 由于Clock 需要显示当前时间,所以使用包含当前时间的对象来初始化 this.state 。 我们稍后会更新此状态。

  2. React 然后调用 Clock 组件的 render() 方法。这是 React 了解屏幕上应该显示什么内容,然后 React 更新 DOM 以匹配 Clock 的渲染输出。

  3. 当 Clock 的输出插入到 DOM 中时,React 调用 componentDidMount() 生命周期钩子。 在其中,Clock 组件要求浏览器设置一个定时器,每秒钟调用一次 tick()

  4. 浏览器每秒钟调用 tick() 方法。 在其中,Clock 组件通过使用包含当前时间的对象调用setState() 来调度UI更新。 通过调用 setState() ,React 知道状态已经改变,并再次调用render() 方法来确定屏幕上应当显示什么。 这一次,render() 方法中的this.state.date 将不同,所以渲染输出将包含更新的时间,并相应地更新DOM。

  5. 一旦Clock组件被从DOM中移除,React会调用componentWillUnmount()这个钩子函数,定时器也就会被清除。

数据自顶向下流动

父组件或子组件都不能知道某个组件是有状态还是无状态,并且它们不应该关心某组件是被定义为一个函数还是一个类。

这就是为什么状态通常被称为局部或封装。 除了拥有并设置它的组件外,其它组件不可访问。

function FormattedDate(props) {  //组件可以选择将其状态作为属性传递给其子组件
  return 

It is {props.date.toLocaleTimeString()}.

; // } class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return (

Hello, world!

{/*子组件接收当前组件的state,FormattedDate 组件将在其属性中接收到 date 值,并且不知道它是来自 Clock 状态、还是来自 Clock 的属性、亦或手工输入*/}
); } } ReactDOM.render( , document.getElementById('root') );

这通常被称为自顶向下单向数据流。 任何状态始终由某些特定组件所有,并且从该状态导出的任何数据或 UI 只能影响树中下方的组件。

如果你想象一个组件树作为属性的瀑布,每个组件的状态就像一个额外的水源,它连接在一个任意点,但也流下来。


为了表明所有组件都是真正隔离的,我们可以创建一个 App 组件,它渲染三个Clock

function FormattedDate(props) {
  return 

It is {props.date.toLocaleTimeString()}.

; } class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return (

Hello, world!

); } } function App() { return (
); } ReactDOM.render(, document.getElementById('root'));

你可能感兴趣的:(React学习)