React学习(一)

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

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

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

 

二. createClass用于生成组件类

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

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

(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验证组件类传入的属性是否符合要求

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,它可以极大提高网页性能。

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

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
posted @ 2018-10-31 11:07  tracy-ling  阅读(142)  评论(0编辑  收藏  举报