React Native入门学习笔记三(JSX语法)

前端之家收集整理的这篇文章主要介绍了React Native入门学习笔记三(JSX语法)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参考示例:
https://github.com/ruanyf/react-demos

demo1 javascript/babel

很简单,react的jsx语法 与js不同,引用的script标签要这样写:

<script type="text/babel"></script>
<!DOCTYPE html>
<html>
  <head>
    <script src="../build/react.js"></script>
    <script src="../build/react-dom.js"></script>
    <script src="../build/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel"> // ** Our code goes here! ** </script>
  </body>
</html>

demo2 简单数组遍历

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

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

render函数遇到

就按html解析,如果遇到{}就按js解析。

demo3 直接嵌入数组

var arr = [
  <h1>Hello world!</h1>,<h2>React is awesome</h2>,];
ReactDOM.render(
  <div>{arr}</div>,document.getElementById('example')
);

这时会直接展开数组内容

demo4 创建component组件类

使用React.createClass。

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

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

所有组件类必须有render方法
组件类第一个字母必须大写;
组件类只能有一个顶层标签
组件的属性在组件对象的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
);

子节点可能是undefined/object/array。可以使用React.Children.map遍历子节点避免undefined的情况。

demo05 React.Children.map

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.getElementById('example')
);

React.children有另外几种方法
map
forEach
count
only
toArray
可参考:https://facebook.github.io/react/docs/top-level-api.html#react.children

demo06 protoTypes验证

以下示例当title值为数值时,控制台会输出错误

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

demo07 查找dom

以下示例使用ref查找真实的dom节点。dom节点从虚拟节点到插入到真实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>
    );
  }
});

ReactDOM.render(
  <MyComponent />,document.getElementById('example')
);

上面使用了click事件,除此之外,还有react还支持onClick,onKeyDown,onCopy等事件,参考文档:http://facebook.github.io/react/docs/events.html#supported-events

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

demo09 表单

以下示例使用event.target.value获取文本框的值。

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.getElementById('example'));

更多form组件参考:http://facebook.github.io/react/docs/forms.html

demo10 组件生命周期

组件生命周期分为三种状态:

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

以下五个主要事件:

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate(object nextProps,object nextState)
  • componentDidUpdate(object prevProps,object prevState)
  • componentWillUnmount()

还有两个特殊状态事件:

  • 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.getElementById('example')
);

demo11 ajax

以下示例,使用 componentDidMount 方法设置 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI 。ajax请求部分使用了jQuery库。

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.getElementById('example') );

demo12 promise

下面示例把异步ajax作为组件的属性

ReactDOM.render(
  <RepoList  promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')} />,document.body
);

根据ajax的状态,显示loading,error或结果。

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>
      );
    }
  }
});
原文链接:https://www.f2er.com/react/306562.html

猜你在找的React相关文章