说说React的事(四)State和Props

说说React的事

Winter

2017-10-11

在React里,我们经常会和两个基本特性State和Props打交道。

State

React把用户的界面当做是状态机,State是React组件中的一个对象,改变这个状态State时然后再去渲染这个状态时,就可以引起界面做出相应的改变,使得页面和数据保持一致。

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
		
      this.state = {
         header: "Header from state...",
         content: "Content from state..."
      }
   }
	
   render() {
      return (
         <div>
            <h1>{this.state.header}</h1>
            <h2>{this.state.content}</h2>
         </div>
      );
   }
}

export default App;

运行这段代码后我们将看到页面有h1标签显示Header from state...和h2标签显示Content from state...,我们通过this.setState方法来改变state状态并引起页面重新渲染。比如上面的代码片段中假如给h1添加一个点击方法,然后点击h1执行以下的代码,那h1标签将会变为显示hello world。

this.setState({header:"hello world"});

这里要注意的是,每次调用this.setState都会触发页面重新渲染,即render方法都会被执行一次。所以千万不能再render方法中显性或隐性的调用this.setState方法。

Props

父组件向子组件传递数据的方式就是通过Props,我们知道React是一种单向数据流的框架,而这个Props就是连接父组件和子组件数据流之间的一座桥梁,而且传递给子组件Props数据是只读,子组件不能再改变Props中的值。如下所示父组件App向子组件Header和Content传递数据:

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <Header title="I'm tilte"/>
            <Content subtitle="I'm subtitle" content="hello world"/>
         </div>
      );
   }
}

class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.title}</h1>
         </div>
      );
   }
}

class Content extends React.Component {
   render() {
      return (
         <div>
            <h2>{this.props.subtitle}</h2>
            <p>{this.props.content}</p>
         </div>
      );
   }
}

export default App;

运行该代码片段:

I'm tilte

I'm subtitle

hello world

第24篇《说说React的事(四)State和Props》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0条评论