React前端开发Web 前端开发

react 学习笔记

2016-08-18  本文已影响580人  SCQ000

workspace setup 安装和使用

​ html文档中需要引入react.js react-dom.js 以及babel等文件

​ 采用JSX语法 <script type="text/babel">

components & rendering 组件渲染

var CommentBox = React.createClass({
  render: function() {
    return (
        <div className="commentBox">Hello world!</div>
    );
  }
});

ReactDom.render(
  <CommentBox />,
  document.getElementById('content')
);

获取DOM元素节点,并将组件渲染上去。

composing multiple react components 组合多组件

var CommentList = React.createClass({
  render: function() {
    return (<div className="commentList">Hello, I am a CommentList</div>);
  }
});

var CommentForm = React.createClass({
  render: function() {
    return (<div className="commentForm">Hello, I am a CommentForm.</div>);
  }
});
var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        <CommentForm />
      </div>
    );
  }
});

在组合组件中,React会自动调用createElement(tagName)方法来渲染DOM节点。

state vs props & application data

React中的数据可以通过state和props两个属性值来获取。

props

props是一种从父级向子级传递数据的方式。而state仅用于交互功能,即数据随着时间变化。

给Comment控件添加一些属性

var Comment = React.createClass({
  render: function() {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
            {this.props.author}
        </h2>
        {this.props.children}
      </div>
    );
  }
});

使用过程中,React会检测到定义的属性值

var CommentList = React.createClass({
  render: function() {
    return (
      <div className="commentList">
        <Comment author="Pete Hunt">This is one comment</Comment>
        <Comment author="Jordan Walke">This is *another* comment</Comment>
      </div>
    );
  }
});

this.props.author的值会有["Pete Hunt", "Jordan Walke"]

this.props.children则表示了组件的所有子节点,当子节点个数大于1时,可以使用map 方法来处理相关逻辑。

adding markdown

可以给组件加上markdown格式支持

var Comment = React.createClass({
  render: function() {
    return (
      var md = new Remarkable();
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        {md.render(this.props.children.toString())}
      </div>
    );
  }
});

application data 直接渲染数据

var data = [
  {id: 1, author: "Pete Hunt", text: "This is one comment"},
  {id: 2, author: "Jordan Walke", text: "This is *another* comment"}
];

var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.props.data} />
        <CommentForm />
      </div>
    );
  }
});

ReactDom.render(
  <CommentBox data={data} />,
  document.getElementById('content')
);

可以动态地渲染CommentList组件

var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function(comment) {
      <Comment author={comment.author} key={comment.id}>
        {comment.text}
      </Comment>
    });

    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

state

state属性是组件的私有变量,表示了组件的状态。当组件的状态更新的时候,组件会重新渲染自身。

var CommentBox = React.createClass({
  //获取初始化状态,只执行一次
  getInitialState: function() {
    return {data: []};
  },
  //当组件加载后,获取数据
  componentDidMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        /*从组件状态获取数据*/
        <CommentList data={this.state.data} />
        <CommentForm />
      </div>
    );
  }
});

由于componentDidMount是在React被渲染后第一次执行的,所以可以利用setInterval方法每隔一段时间从服务器获取最新的数据

var CommentBox = React.createClass({
  loadCommentsFromServer: function() {
    $.ajax(...);
  },
  componentDidMount: function() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },
  ...
  ...
});

ReactDom.render(
  <CommentBox url="/url/comments" pollInterval={2000} />,
  document.getElementById('content')
);

javascript events & data changes 事件和数据更新

var CommentForm = React.createClass(function() {
  getInitialState: function() {
    return {author: '', text: ''};
  },
  handleAuthorChange: function(e) {
    this.setState({author: e.target.value});
  },
  handleTextChange: function(e) {
    this.setState({text: e.target.value});
  },
  render: function() {
    return (
      <form className="commentForm">
        <input type="text" placeholder="Your name" value={this.state.author} onChange={this.handleAuthorChange}/>
        <input type="text" placeholder="Say something" value={this.state.text} onChange={this.handleTextChange}/>
        <input type="submit" value="Post" />
      </form>
    )
  };
});

events 事件处理

事件处理是利用setState方法来更新组件状态,其中组件中onChange属性用来触发定义的事件监听器。

...
//处理submit方法
handleSubmit: function() {
  e.preventDefault();
  var author = this.state.author.trim();
  var text =  this.state.text.trim();
  if(!text || !author) {
    return;
  }
  this.setState({author: '', text: ''});
},
render: function() {
  return (
    <form className="commentForm" onSubmit={this.handleSubmit}>
      ....
    </form>
  )
}

React中绑定事件处理器是使用驼峰命名法的方式。

要在手机或平板上使用触摸事件,需要调用React.initalizeTouchEvents(true)方法

Prop验证

React.PropTypes提供很多验证其来验证传入数据的有效性。

React.createClass({
  propTypes: {
    optionalArray: React.PropTypes.array,
    optionalBool: React.PropTypes.bool,
    optionalFunc: React.PropTypes.func,
    optional....

    optionalNode: React.PropTypes.node,

    //自定义验证器
    customProp: function(props, propName, componentName) {
      if(!/matchme/.test(props[propName])) {
        return new Error('Validation failed!');
      }
    }
  },

  ...

})

默认prop值

var ComponentWithDefaultProps = React.createClass({
  getDefaultProps: function() {
    return {
      value: 'default value'
    };
  },
});
上一篇 下一篇

猜你喜欢

热点阅读