React框架的基本使用和了解

React:

React详解:

安装react 脚手架工具:

npm install -g create-react-app

create-react-app 项目名称

cnpm react-dom -install -S 安装专门进行DOM操作的最主要的应用场景,即ReactDOM.render()

<script type=”text/babel”>

react相关的模板写在其中。

</script>

2

允许直接在模板中插入javascript变量,如果变量是一个数组,则会展开这个数组的所有成员。

例如:

var arr = [

  <h1>Hello world!</h1>,

  <h2>React is awesome</h2>,];

ReactDOM.render(

  <div>{arr}</div>,

  document.getElementById('example'));

 

3 :组件:

React 允许将代码封装成一个组件,最后在网页中插入这个组件。使用React.createClass():

var HelloMessage = React.createClass({

  render: function() {

    return <h1>Hello {this.props.name}</h1>;

  }});

 

ReactDOM.render(

  <HelloMessage name="John" />,

  document.getElementById('example'));

所有的组件类都必须有自己的render方法,用于输出组件。

注意:1 组件类的第一个字母必须大写. 2 组件类必须只能包含一个顶层标签。

组件在使用时可以加上任何属性,  同时组件的属性可以通过this.props 对象上获取。

添加组件属性需要注意的地方: 1 class属性需要写成classNameFor属性需要写成htmlFor  主要是因为classfor属性是JavaScript的保留字。

二:this.props.children 属性:表示组件的所有子节点。通过this.props.children属性可以访问到组件的所有子组件的相关属性。

如果当前组件没有子节点:this.props.children 的值为undefined

如果当前组件只有一个子节点: this.props.children的数据类型为object

如果当前组件有多个子节点 那么this.props.children数据类型就是Array.

 

PropTypes属性 :该属性用于验证当别人使用组件时,提供的参数是否符合要求。

示例:  该组件要求title属性必须是string类型的,且是必须要填写的。

var MyTitle = React.createClass({

  propTypes: {

    title: React.PropTypes.string.isRequired,

  },

 

  render: function() {

     return <h1> {this.props.title} </h1>;

   }});

getDefaultProps方法可以用来设置组件属性的默认值。

示例:


var MyTitle = React.createClass({

  getDefaultProps : function () {

    return {

      title : 'Hello World'

    };

  },

 

  render: function() {

     return <h1> {this.props.title} </h1>;

   }});

 

ReactDOM.render(

  <MyTitle />,

  document.body);

上述渲染出来的结果是默认设置的Hello World

获取真实的DOM节点:

通过ref属性来获取。

示例:


var MyComponent = React.createClass({

  handleClick: function() {

    this.refs.myTextInput.focus();

  },

  render: function() {

    return (

      <div>

        <input type="text" ref="myTextInput" />

        <input type="button" value="Focus the text input" onClick={this.handleClick} />

      </div>

    );

  }});

 

ReactDOM.render(

  <MyComponent />,

  document.getElementById('example'));

通过this.refs.[refName] 属性 来读取到真正的DOM节点。

 

React组件支持除了click事件之外的许多其他组件, 例如 KeyDown Copy Scroll 等  详细的React事件 可访问:

https://reactjs.org/docs/events.html#supported-events

四:this.state:

组件开始有一个初始的状态,然后用户互动,导致状态的变化,从而触发重新渲染UI

示例:


var LikeButton = React.createClass({

  getInitialState: function() {

    return {liked: false};

  },

  handleClick: function(event) {

    this.setState({liked: !this.state.liked});

  },

  render: function() {

    var text = this.state.liked ? 'like' : 'haven\'t liked';

    return (

      <p onClick={this.handleClick}>

        You {text} this. Click to toggle.

      </p>

    );

  }});

 

ReactDOM.render(

  <LikeButton />,

  document.getElementById('example'));

首先通过getInitialState方法用于定义初始状态。通过this.state属性读取值。通过this.setState方法就可以修改状态的值。 每次修改以后通过this.render()方法重新渲染组件。

This.props this.state的主要区别在于:this.props 表示那些一旦定义,就不再改变的特性,而 this.state 是会随着用户互动而产生变化的特性。

五:表单:

用户在表单填入的内容属于用户跟组件的互动。所以不能够使用this.props读取。

示例:

var Input = React.createClass({

  getInitialState: function() {

    return {value: 'Hello!'};

  },

  handleChange: function(event) {

    this.setState({value: event.target.value});

  },

  render: function () {

    var value = this.state.value;

    return (

      <div>

        <input type="text" value={value} onChange={this.handleChange} />

        <p>{value}</p>

      </div>

    );

  }});

 

ReactDOM.render(<Input/>, document.body);

上述表单中,定义一个onChange事件的回调函数,通过event.target.value读取用户输入的值。textarea,select,radio 元素都属于这种情况。

六:组件的生命周期:

首先组件的生命周期分成三个状态:

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

同时React 为每个状态都提供了两种处理函数: will 函数在进入状态之前调用。did函数在进入状态之后调用。

componentWillMount()

componentDidMount()

componentWillUpdate(object nextProps, object nextState)

componentDidUpdate(object prevProps, object prevState)

componentWillUnmount()

此外 React 还提供了两种特殊状态的处理函数。

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
  • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用

示例:


var Hello = React.createClass({

  getInitialState: function () {

    return {

      opacity: 1.0

    };

  },

 

  componentDidMount: function () {

    this.timer = setInterval(function () {

      var opacity = this.state.opacity;

      opacity -= .05;

      if (opacity < 0.1) {

        opacity = 1.0;

      }

      this.setState({

        opacity: opacity

      });

    }.bind(this), 100);

  },

 

  render: function () {

    return (

      <div style={{opacity: this.state.opacity}}>

        Hello {this.props.name}

      </div>

    );

  }});

 

ReactDOM.render(

  <Hello name="world"/>,

  document.body);

注意:style属性的设置方式为:

style={{opacity: this.state.opacity}}

 

 Ajax请求的数据来源:

组件的数据来源,通常是通过 Ajax 请求从服务器获取,可以使用 componentDidMount 方法设置 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI

请求数据时,在componentDidMount函数中进行。

示例:

var UserGist = React.createClass({

  getInitialState: function() {

    return {

      username: '',

      lastGistUrl: ''

    };

  },

 

  componentDidMount: function() {

    $.get(this.props.source, function(result) {

      var lastGist = result[0];

      if (this.isMounted()) {

        this.setState({

          username: lastGist.owner.login,

          lastGistUrl: lastGist.html_url

        });

      }

    }.bind(this));

  },

 

  render: function() {

    return (

      <div>

        {this.state.username}'s last gist is

        <a href={this.state.lastGistUrl}>here</a>.

      </div>

    );

  }});

 

ReactDOM.render(

  <UserGist source="https://api.github.com/users/octocat/gists" />,

  document.body);

 

将一个promise对象传入组件:

 

ReactDOM.render(

  <RepoList

    promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')}

  />,

  document.body);

如果Promise对象正在抓取数据(pending状态),组件显示"正在加载";如果Promise对象报错(rejected状态),组件显示报错信息;如果Promise对象抓取数据成功(fulfilled状态),组件显示获取的数据。


var RepoList = React.createClass({

  getInitialState: function() {

    return { loading: true, error: null, data: null};

  },

  componentDidMount() {

    this.props.promise.then(

      value => this.setState({loading: false, data: value}),

      error => this.setState({loading: false, error: error}));

  },

  render: function() {

    if (this.state.loading) {

      return <span>Loading...</span>;

    }

    else if (this.state.error !== null) {

      return <span>Error: {this.state.error.message}</span>;

    }

    else {

      var repos = this.state.data.items;

      var repoList = repos.map(function (repo) {

        return (

          <li>

            <a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description}

          </li>

        );

      });

      return (

        <main>

          <h1>Most Popular JavaScript Projects in Github</h1>

          <ol>{repoList}</ol>

        </main>

      );

    }

  }});

posted @ 2021-01-22 18:51  TangTaue  阅读(319)  评论(0编辑  收藏  举报