React(一)

1、导入组件,import from 'xxxx'的用法详解

参考:https://blog.csdn.net/chevins/article/details/51523770

import React, { Component } from 'react';

这是RN 0.26后导入React的方式,这意思是,导入‘react’文件里export的一个默认的组件,将其命名为React以及Component这个非默认组件

import Home from './compoments/Home';

这是导入‘compoments/Home’文件里export的带default关键字的组件,即默认组件,将其命名为Home(可以自定义命名)

1.2、学习react的前提:


jsx 是Facebook为react开发的一套语法糖,

CoffeeScript

TypeScript

这三者最终被解释成js才能被理解和执行。

2、JSX中"{}"表示要执行js一个表达式的值

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

this表示当前react component实例

props是在我们使用react component时,在其上添加的属性的集合;他的key值和value值跟下面的<Hello name="World"/>是一一对应的 。

class:在js语言的ES6标准里已经成为了关键字 ;用来声明一个类;在js的运行环境不能直接写一个类;若要声明标签的类名则需要写成className

<hello name=""/>:hello是HTML标签的自定义标签

render() 中的<div>和<hello>是react component实例

react中,行内样式,是不能使字符串的。必须是个对象。注意一个"{}"表示执行js表达式,js表达式是一个对象,所以在直接写属性的时候,需要"{{}}".比如


return <div style={{color:"red"}}>hello.......

2、react component的生命周期



hook()函数,最早是用来指windows中提供的用于替换dos下的中断的系统机制;现在是泛指,中文是钩子。

在对特定的事件进行hook后,一旦发生以hook事件对该事件进行hook的程序,就会受到系统的通知,这时候程序就能在第一时间内对该事件作出响应;对于每一种状态react封装了多个hook函数、

在mountd阶段,getInitialState:function(){},componentWillMount:function(){},componentDidMount:function(){}需要放到React.createClass({})中。在点击运行时,react会尝试获取component  getInitialState:function(){}、然后componetWillMount:function()阶段,最后是componentDidMount阶段。其中getInitialState可以来初始化一些components,在render:function(){}中component中写style={this.state}或者{{opacity:this.state.opacity}}


properties和state的区别:

properties通常是通过组件调用方在调用组件时候用到,properties一旦指定了在一般情况下是不变的;尤其是对于被调用组件来说,这个properties的拥有者是其调用方;在其结构上是其parent。

而state是私属于当前组件的;state值是可变的;

修改state的值:

首先把this对象的应用拿到,this在windows.setTimeout(function(){})之外时,this表示当前component实例,否则this表示当前函数的label对象;然后设置定时器1s以后windows.setTimeout(function(){_self.setState({  opacity:0.5,fontSize:'44px'});

this是js课程中指代。this本身代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。随着函数使用场合不同,this的值会变话,但总的原则时,this指的是调用函数的对象。当this出现在函数参数中时,函数参数就是纯粹的函数调用。不隶属于那个对象。所以属于全局性调用,此时this指的是全局对象global。


this出现在构造函数中时,


this 调用函数的apply,call , bind,方法,其作用是改变函数的调用对象。第一个参数就是表示改变后的调用这个函数的对象。因此this指的就是这第一个参数。


function外面的this是component实例;注意bind(this)ES5中才有。component的state值的变化都会导致component从当前值状态进入updating;从而重新render;没有显示的修改样式,但是state值变了其样式也会做相应的修改。


3、react的事件:

传统的页面更新DOM是:通过innerHTML或者修改DOM节点的classname等;

绑定事件传统做法是:element.addEventListener();//按钮,键盘触发,动画开始等;

react component事件绑定和处理:

一个事件对应一个组件来写。

4、NodeJs基于browser-sync服务




然后将node.js的package.json 修改为:




5、React实例:https://cdnjs.com/libraries/react/0.13.3中下载

script引得那些js,可以从:

react实例:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

    function formatName(user) {
      return user.firstName + ' ' + user.lastName;

    }
    function getGreeting(user){
      if (user){
        return <h1>Hello,{formatName(user)}!</h1>;
      }
      return <h1> Hello,Stranger.</h1>;
    }
    const user = {
      firstName: 'Harper',
      lastName: 'Perez',
    };

    const element = <h1>Hello, {getGreeting(user)}</h1>;

    ReactDOM.render(element, document.getElementById('root'));

    </script>
    <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.

      To set up a production-ready React build environment, follow these instructions:
      * https://reactjs.org/docs/add-react-to-a-new-app.html
      * https://reactjs.org/docs/add-react-to-an-existing-app.html

      You can also use React without JSX, in which case you can remove Babel:
      * https://reactjs.org/docs/react-without-jsx.html
      * https://reactjs.org/docs/cdn-links.html
    -->
  </body>
</html>

在运行程序时,先启动browser-sync服务:


运行结果:



6、浏览React官方文档时,一些前置知识的积累:

6.1、tabindex属性:


<!DOCTYPE html>
<html>
<body>

<a href="http://www.w3school.com.cn/" tabindex="2">W3School</a><br />
<a href="http://www.google.com/" tabindex="1">Google</a><br />
<a href="http://www.microsoft.com/" tabindex="3">Microsoft</a>

<p><b>注释:</b>请尝试使用键盘上的 "Tab" 键在链接之间进行导航。</p>

</body>
</html>

6.2、jsx防止注入:

 /*原理就是每个进行渲染必须是显式定义的字符串,要接收到的可能含有危险内容的字符串放入大括号中,这是比较安全的做法
        const title=response.potentiallyMaliciousInput;
        const element=<h1>{title}</h1>*/

不懂啊!没弄出来!

6.3、

问题:

自己之前有个react的HTML实例,现在自己又新建了一个,为什么启动browser-sync 运行的还是之前那个HTML呐?

6.4、nodejs中package.json的作用:

参考自:https://segmentfault.com/q/1010000002629038


6.5、js中时间的获得:


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      这是一个时钟
    </title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      function tick(){
        // const element=(
        //   <div>
        //     <h1>Hello,World!</h1>
        //     <h2>It is {new Date().toLocaleTimeString()}.</h2>
        //   </div>
        // );

        //ReactDOM.render(element,document.getElementById('root'));
        var d = new Date();
        alert(d);
        var x = document.getElementById("root");
        x.innerHTML=d.toLocaleTimeString();
      }
      setInterval(tick,1000);
    </script>
  </body>
</html>

运行结果:


即每隔一秒就出现个对话框


用react 就会实时更新:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      这是一个时钟
    </title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      function tick(){
        const element=(
          <div>
            <h1>Hello,World!</h1>
            <h2>It is {new Date().toLocaleTimeString()}.</h2>
          </div>
        );
        ReactDOM.render(element,document.getElementById('root'));
        // var d = new Date();
        // alert(d);
        // var x = document.getElementById("root");
        // x.innerHTML=d.toLocaleTimeString();
      }
      setInterval(tick,1000);
    </script>
  </body>
</html>

秒数是动态的变化


首先,我们讲到的是如果开启定时器

  setInterval  间隔型,应用:无缝滚动、网站时钟
  setTimeout  延时型,应用:QQ头像应用

停止定时器

  clearInterval
  clearTimeout

两种定时器的区别:

  简单的说,setInterval会在设定的时间自动重复,setTimeout不会重复而具有延时性。

7、 Local state is exactly that: a feature available only to classes.

The only place where you can assign this.state is the constructor.

8、Handling Events: 

存在的问题:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      这是一个时钟
    </title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      // class Toggle extends React.Component{
      //   constructor(props){
      //     super(props);
      //     this.state={isToggleOn:true};
      //     // This binding is necessary to make `this` work in the callback
      //     this.handleClick=this.handleClick.bind(this);
      //   }
      //   handleClick(){
      //     this.setState(prevState=>({//这个函数的prevState是React框架帮你保存和传递的,你不用传。第一个参数prevState就是上面设置的this.state。
      //       isToggleOn:!prevState.isToggleOn
      //     }));
      //   }
      //   render(){
      //     return (
      //       <button onClick={this.handleClick}>
      //       {this.state.isToggleOn?'ON':'OFF'}
      //       </button>
      //     );
      //   }
      //
      // }
      //ReactDOM.render(<Toggle/>,document.getElementById('root'));
      class LoggingButton extends React.Component{
        handleClick(){
          console.log('this is :',this);
        }
        render(){
          return (
            <button onClick={(e)=>this.handleClick(e)}>
            Click me
            </button>
          );
        }
      }
      ReactDOM.render(<LoggingButton/>,document.getElementById('root'));
    </script>
  </body>
</html>

运行结果为:


存在的隐患:


9、Form

9.1、input标签:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      这是一个时钟
    </title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </title>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      class NameForm extends React.Component{
        constructor(props){
          super(props);
          this.state={value:''};
          this.handleChange=this.handleChange.bind(this);
          this.handleSubmit=this.handleSubmit.bind(this);
        }
        handleChange(event){
          this.setState({value:event.target.value});
        }
        handleSubmit(event){
          alert('A name was submitted:'+this.state.value);
          event.preventDefault();
        }
        render(){
          /*
          input是标签。拥有元素:文本框、密码、单选框、复选框、按钮等
type是input标签的属性,区别不同的元素
          onchange是form中的动作触发事件:在元素值被改变时运行的脚本。handleChange每次击键时都会运行以更新React状态
          onSubmit:在提交表单时触发。
          */
          return (
            <form onSubmit={this.handleSubmit}>
              <label>
                Name:
                <input type="text" value={this.state.value} onChange={this.handleChange}/>
              </label>
              <input type="submit" value="Submit"/>
            </form>
          )
        }

      }
      ReactDOM.render(
        <NameForm />,
        document.getElementById('root')
      );

    </script>
  </body>
</html>

运行结果


9.2、textarea标签:局部代码

<script type="text/babel">
    class EssayForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 'Please write an essay about your favorite DOM element.'
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('An essay was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Essay:
          <textarea value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

    ReactDOM.render(
          <EssayForm  />,
          document.getElementById('root')
        );
    </script>

运行结果:

 9.3、type="checkbox"时:

HTML:

<html>
<body>

<form action="/example/html/form_action.asp" method="get">
  <p><input type="checkbox" name="vehicle" value="Bike" /> I have a bike</p>
  <p><input type="checkbox" name="vehicle" value="Car" checked="checked" /> I have a car</p>
  <input type="submit" value="Submit" />
</form>

<p>请在提交按钮上单击,输入会发送到服务器上名为 "form_action.asp" 的页面。</p>

</body>
</html>


全选时:



9.4、type="number"类型:

<!DOCTYPE html>
<html>
<body>

<h3>演示如何访问 Number 字段</h3>

<input type="number" id="myNumber" value="2">

<p>点击按钮来获得 number 字段的数字。</p>

<button οnclick="myFunction()">试一下</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myNumber").value;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

运行结果:



9.5、React  number和checkbox的实验:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      这是一个时钟
    </title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </title>
  </head>
  <body>
    <!--结果只是1-->
    <div id="root"></div>
    <script type="text/babel">
    class Reservation  extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            isGoging: true,
            numberOfGuests:2
          };
          this.handleInputChange = this.handleInputChange.bind(this);
        }

        handleInputChange(event) {
          const target=event.target;
          const value=target.type==='checkbox'?target.checked:target.value;
          const name=target.name;
          this.setState({[name]: value});
        }
        render() {
          return (
            <form >
              <label>
                Is going:
                <input name="isGoging" type="checkbox" checked={this.state.isGoing} onChange={this.handleInputChange}/>
              </label>
              <br />
              <label>
                  Number of guests:
                <input type="number" name="numberOfGuests"  value={this.state.numberOfGuests} onChange={this.handleInputChange}  />
              </label>
            </form>
          );
        }
      }
    ReactDOM.render(
          <Reservation  />,
          document.getElementById('root')
        );
    </script>
  </body>
</html>

运行结果:


不是很理解:

handleInputChange(event) {
          const target=event.target;
          const value=target.type==='checkbox'?target.checked:target.value;
          const name=target.name;
          this.setState({[name]: value});
        }

9.6、fieldset标签:

js中parseFloat()函数:

转自:https://zhidao.baidu.com/question/542226662.html


React代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      这是一个时钟
    </title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    </title>
  </head>
  <body>
    <!--结果只是1-->
    <div id="root"></div>
    <script type="text/babel">
        function BoilingVerdict(props) {
          if (props.celsius >= 100) {
            return <p>The water would boil.</p>;
          }
          return <p>The water would not boil.</p>;
        }


        class Calculator extends React.Component {
            constructor(props) {
              super(props);
              this.handleChange = this.handleChange.bind(this);
              this.state = {temperature: ''};
            }

            handleChange(e) {
              this.setState({temperature: e.target.value});
            }

            render() {
              //<!--BoilingVerdict随着input的按键的数字值而实时改变-->
              const temperature = this.state.temperature;
              return (
                <fieldset>
                  <legend>Enter temperature in Celsius:</legend>
                  <input
                    value={temperature}
                    onChange={this.handleChange} />

                  <BoilingVerdict
                    celsius={parseFloat(temperature)} />
                </fieldset>
              );
            }
          }
          ReactDOM.render(<Calculator/>,document.getElementById('root'));
    </script>
  </body>
</html>

运行结果为:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值