react 知识点

1.ReactDOM.render

ReactDOM.render 是 React 的最基本方法,用于将模板转为 HTML 语言,并插入指定的 DOM 节点。

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

2.JSX 语法

<表示标签,{表示遇到代码块

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

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

3.组件React.createClass

class属性需要写成 className,for属性需要写成 htmlFor

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

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

4.this.props.children

this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性。它表示组件的所有子节点


var NotesList = React.createClass({
  render: function() {
    return (
      <ol>
      {
        React.Children.map(this.props.children, function (child) {
          return <li>{child}</li>;
        })
      }
      </ol>
    );
  }
});

ReactDOM.render(
  <NotesList>
    <span>hello</span>
    <span>world</span>
  </NotesList>,
  document.body
);

5.PropTypes

组件的属性可以接受任意值,字符串、对象、函数等等都可以。有时,我们需要一种机制,验证别人使用组件时,提供的参数是否符合要求。

var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },

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

6.**获取真实的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')
);

7.状态机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')
);

8.表单** 和onChange结合使用

\用户在表单填入的内容,属于用户跟组件的互动,所以不能用 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);

9.组件的生命周期

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

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={{opacity: this.state.opacity}}

10.Ajax

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

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

1.props和state的区别

don't use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time
State 仅仅用在交互性的操作中。

//是不是从props属相传递过来的 
Is it passed in from a parent via props? 
If so, it probably isn't state.
//是不是一直未变化
Does it remain unchanged over time? 
If so, it probably isn't state.
//是不是基于其他的state或者props
Can you compute it based on any other state or props in your component?
If so, it isn't state.

2.自上而下 or 自下而上设计

In simpler examples, it's usually easier to go top-down, and on larger projects, it's easier to go bottom-up and write tests as you build.
在简单的应用中适合自上而下的设计,在复杂的应用中适合自下而上设计组件。

3.如何确定state的归属

Identify every component that renders something based on that state.
//最上面的一个,一般是共有的
Find a common owner component (a single component above all 
the components that need the state in the hierarchy).

Either the common owner or another component higher up in the 
hierarchy should own the state.
//如果不确定就自己创建一个
If you can't find a component where it makes sense to own the
state, create a new component simply for holding the state and
 add it somewhere in the hierarchy above the common owner 
component.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.immutable 连续看了两三篇关于immutable.js的文章,传统的object和array等引用类型...
    别过经年阅读 1,074评论 0 2
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 2,980评论 1 18
  • 现在最热门的前端框架,毫无疑问是 React 。上周,基于 React 的 React Native 发布,结果一...
    sakura_L阅读 503评论 0 0
  • 好快就到了K8营读书的最后一天,每天读大冰一个故事,今天的故事名字叫【小慈悲】,老潘是故事的主人公,在大冰笔下,感...
    Justina_Fu阅读 403评论 2 0
  • 不知谁说我们的大脑只被开发了1%,这句话的真实性我没有去考查。 但一定程度上,我相信它是对的,从我们对自己的无意识...
    脱兔的五味杂陈阅读 793评论 0 1

友情链接更多精彩内容