一、引入 js 文件
页面中 react 写法:
- <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
- <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
- <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
create-react-app 中写法:
- const aa = {};
- const bb = {};
- exports aa;
- exports bb;
现在将 hello.js 引入到 world.js 中:
- import Hello from 'hello.js';
Hello 就好好比于:
- Hello = {
- aa: {},bb: {}
- }
在 world.js 中要想调用 aa 对象就得使用 Hello.aa;
将 hello.js 引入到 world.js 中的另一种写法:
- import Hello,{aa} from 'hello.js';
此时在 world.js 中要想调用 aa 对象就可以直接使用 aa。
{aa} 语法表示直接将 Hello 对象内部的自变量 aa 给暴露了出来。
二、创建组件
ES6 语法中函数可以省略 function。
- render () {}
- 原本应该是
- function render () {}
页面中 react 写法:
- var HelloWorld = React.createClass({
- render: function () {
- return (
- <div>
- <h1>Hello,{this.props.name}</h1>
- </div>
- );
- }
- });
create-react-app 中写法:
- class HelloWorld extends Component {
- render () {
- return (
- <div>
- <h1>Hello,{this.state.name}</h1>
- </div>
- );
- }
- }
- export default HelloWorld; // 将 HelloWorld 给暴露出去
三、数据的类型校验
这里的数据指从外层组件传递进来的属性。
可以在 this.props 对象中获取。内部调用属性值: this.props.name
页面中 react 写法:
- var Name = React.createClass({
- propTypes: {
- name: React.PropTypes.number
- },render: function () {
- return <h1>Hello,{this.props.name}</h1>
- }
- });
create-react-app 中写法:
- class Name extends Component {
- static propTypes = {
- name: PropTypes.number.required
- }
- render () {
- return <h1>Hello,{this.props.name}</h1>
- }
- }
- export default Name;
四、设置状态值
子组件自身可以设置状态值,但属性值只能通过外层组件传入。
内部调用状态值 this.state.liked
页面中 react 写法:
- var LikeButton = React.createClass({
- getInitialState: function () {
- return {liked: false};
- },render: function () {
- var text = this.state.liked ? '喜欢' : '不喜欢';
- return <h1>你<b>{text}</b>我,点击我切换状态。</h1>
- }
- });
create-react-app 中写法:
- class LikeButton extends Component {
- constructor (props) {
- super(props);
- this.state = {
- liked: false
- }
- }
- render () {
- const text = this.state.liked;
- return <h1>你<b>{text}</b>我,点击我切换状态。</h1>
- }
- }
- export default LikeButton;