React学习(一)

一. 容许HTML和JavaScript代码混写,使用JSX语法:遇到HTML标签就用HTML规则解析,遇到{}的代码块就用js解析javascript

var names = ['Alice', 'Emily', 'Kate'];

ReactDOM.render(
  <div>
  {
    names.map(function (name) {
      return <div>Hello, {name}!</div>
    })
  }
  </div>,
  document.getElementById('example')
);

 

二. createClass用于生成组件类html

(1)组件类都有一个render方法用于输出组件java

(2)组件类第一个字母必须大写react

(3)组件类只有一个顶层标签算法

(4)组件添加属性,class须要写成className,for须要写成htmlFor。或者使用 style,style赋值不能是字符串,应该是对象形式,key值使用驼峰函数

(5)this.props属性与组件属性一一对应性能

var HelloMessage = React.createClass({
  render: function() {
    return <h1>Hello {this.props.name}</h1>;
  }
});

ReactDOM.render(
  <HelloMessage name="John" />,
  document.getElementById('example')
);

 

三. propTypes验证组件类传入的属性是否符合要求ui

var data = 123;

var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired, //title是必传的字符串,传入123数字控制台会报错
  },

  render: function() {
    return <h1> {this.props.title} </h1>;
  }
});

ReactDOM.render(
  <MyTitle title={data} />,
  document.getElementById('example')
);

 

四. 组价并非真实的DOM,而是在内存中的虚拟DOM,只有组件插入文档,才会变成真实的DOM。根据React设计,全部DOM变更都先在虚拟DOM上进行,再将实际变更部分反映在真实DOM上,这种算法叫DOM Diff,它能够极大提升网页性能。this

经过ref从组件获取真实DOM节点spa

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>
    );
  }
});

 

五. 状态机this.state:组件当作一个状态机,getInitialState定义初始状态,用户互动状态变化,触发从新渲染UI。

属性经过this.state获取,修改属性this.setState

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>
    );
  }
});

 

六. event.target.value 读取用户输入

绑定事件驼峰 onClick={this.handleClick},方法不加括号,加了括号不会在点击时执行,会当即执行

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>
    );
  }
});

 

七. 生命周期函数:componentWillMount、componentDidMount、componentWillUpdate、componentDidUpdate、componentWillUnMount

Mounting:getInitialState、componentWillMount、render、componentDidMount
Updating:componentWillReceiveProps、shouldComponentUpdate、 componentWillUpdate、render、componentDidUpdate
Unmounting:componentWillUnmount 

 

参考:http://www.ruanyifeng.com/blog/2015/03/react.html 
相关文章
相关标签/搜索