Learn react basics first, then use create-React -app scaffolding to generate the development environment

1) You can download the CDN library directly from the React website or Github

< 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 >Copy the code

React.min. js is the react base library, react-dom.min.js provides DOM-related functions, and babel.min.js provides ES6 syntax parsing

2) HTML template

Use the React page source code, structure is roughly as follows.

<! DOCTYPE HTML > < HTML > < head > < 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 > < / head > < body > < div id = "example" > < / div > <script type="text/babel"> // ** Our code goes here! ** </script> </body> </html>Copy the code

Note that the type attribute of the script tag is no longer ‘text/javascript’ but ‘text/ Babel’. This is because React’s unique JSX syntax is incompatible with javascript. Wherever JSX is used, add type= “text/ Babel”.

3) Render function

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

Reactdom.render is the most basic method of React, used to convert templates to HTML and insert specified DOM nodes. Example: Insert an H1 tag into a node whose id is example.

4) JSX syntax

JSX syntax is HTML syntax written directly in javascript without any quotes. It allows HTML to be mixed with JS. When we need to use JS, we just need to “{enclose JS syntax}”.

< div id = "example" > < / div > var names = [' Ming ', 'red', 'xiao LAN']. ReactDOM.render( <div> { names.map((name,index)=>{ return <div data-index={index}>{name}</div> }) } </div>, document.getElementById('example') )Copy the code



5) components

React. CreateClass () Component.component.createclass ()

<div id="example"></div> let Hi = react.createclass ({render: function(){return <div>hello, word</div>}}); ReactDOM.render( <Hi />, document.getElementById('example') )Copy the code

In the code above, the variable Hi is a component class. When a template is inserted, an instance of Hi is automatically generated (” component “below refers to an instance of a component class). All component classes must have their own Render methods to output components. Note that the first letter of a component class must be capitalized, otherwise an error will be reported. For example, Hi cannot be written as Hi. In addition, the component class can contain only one top-level tag, otherwise an error will be reported.

Let Hi = React. CreateClass ({render: function(){return <div>hello, word</div><div>hello, world </div>}});Copy the code

In this case, an error is reported because there is only one layer of top-level tags in the component

5-1. Father-son correspondence

This.props. Property name

<div id="example"></div> let Hi = React.createClass({ render : Function (){return <div>hello, {this.props. Name}</div>}}); <Hi name=" xiaoming "/>, document.getelementById ('example'))Copy the code

6)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 );Copy the code

The NoteList component of the code above has two span children, both of which can be read by this.props. Children. If the current component has no child nodes, it is undefined; If there is a child node, the data type is Object; If there are multiple child nodes, the data type is array. So be careful with this.props. Children. React provides a utility method to handle this.props. Children. We can use react.children. map to traverse child nodes without worrying about whether this. Props.Children is undefined or object. For more on the React.Children method, please refer to the official documentation.

7)PropTypes

PropTypes specifies the data types for parent-child communication

Var MyTitle = React. CreateClass ({propTypes: {title: React. PropTypes. String. IsRequired, / / string type And this property is will pass}, render: function() { return <h1> {this.props.title} </h1>; }}); var data = 123; ReactDOM.render( <MyTitle title={data} /> )Copy the code

This is going to get an error because data is a number property

8) Get real DOM nodes

A component is not a real DOM node, but a data structure that exists in memory, called a virtual DOM. Only when it is inserted into the document does it become a real DOM. React is designed to allow all DOM changes to occur in the virtual DOM and then reflect the actual changes in the real DOM. This algorithm is called DOM Diff and can greatly improve the performance of web pages. However, sometimes you need to get nodes of the real DOM from a component, and that’s when you use the REF attribute

let Hand = React.createClass({ alertfn(){ alert(this.refs.istest.getAttribute('name')) }, render : Function (){return <div> <div name=" x "></div> <button onClick={this.alertfn}>; ReactDOM.render( <Hand />, document.body )Copy the code

The React component supports a wide range of events, including KeyDown, Copy, Scroll, etc. For a complete list of events, see the official documentation.

9) this state

Components have to interact with the user. One of the innovations of React is to treat components as a state machine. They start with an initial state and then the user interacts with them, resulting in state changes that trigger a UI re-rendering

let ChangeState = React.createClass({ getInitialState(){ return {color:false}; }, changeColor(){ this.setState({color : ! this.state.color}) }, render(){ var c = this.state.color ? 'blue' : 'yellow'; return <div> <div style={{height:"30px",background:c}}></div> <button type="button" OnClick ={this.changeColor}> click </button> </div>}}); ReactDOM.render( <ChangeState />, document.body )Copy the code

The getInitialState method in the ChangeState component is used to define the initial state, which is an object that can be read through the this.state property. When a user clicks on a component and the state changes, the this.setState method modifies the state value. After each change, the this.render method is automatically called to render the component again. Because both this.props and this.state are used to describe the features of the component, confusion can arise. An easy way to distinguish this is that this.props represents features that, once defined, do not change, while this.state is a feature that changes with user interaction.

10) form

The VUE framework has a V-Model two-way data binding, while React does not. The v-Model effect can be achieved by listening for the Inputchange event and binding state

var Myform = React.createClass({
        getInitialState(){
        return {message : ''}
    },
    changetext(ev){
    this.setState({message:ev.target.value});
    },
    render(){
    return <div>
        <input type="text" value={this.state.message} onChange={this.changetext} />
        <p>{this.state.message}</p>
    </div>
    }
    });
    ReactDOM.render(
        <Myform />,
        document.body
    )
Copy the code

In the above code, the value of the text input box cannot be read with this.props. Value. Instead, we need to define a callback to the onChange event that reads the value of the user’s input through event.target.value. The Textarea element, the SELECT element, and the radio element are all examples of this. See the official documentation for more information.

11) Component lifecycle

The lifecycle of a component is divided into three states:

  • Mounting: The real DOM is inserted
  • Updating: Being rerendered
  • Unmounting: The real DOM has been removed

React provides two handlers for each state. The will function is called before the state and the DID function is called after the state. There are five handlers for each state.

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

React also provides two special state handlers.

– componentWillReceiveProps (object nextProps) : received a new parameter called when loaded components – shouldComponentUpdate (object nextProps, object nextState) : Called when the component decides whether to rerender

You can refer to the official documentation for detailed explanations of these methods

let Hi = React.createClass({ getInitialState(){ console.log(1) return this.state = { color : 'red' } }, componentWillMount(){ console.log(2) }, componentDidMount(){ console.log(3) }, componentWillUnmount(){ console.log(4) }, Render (){console.log(5) return (<div> test react life cycle {this.state.color}</div>)}}); ReactDOM.render( <Hi />, document.body )Copy the code

Let Hi = react.createclass ({getInitialState(){console.log('------ initializes state ------') return this.state = {test: 'life cycle steps -- ten years'}}, componentWillMount () {the console. The log (' -- -- -- -- -- - mount before -- -- -- -- -- -')}, ComponentDidMount () {the console. The log (' -- -- -- -- -- - mounted end -- -- -- -- -- - ')}, componentWillUnmount () {the console. The log (' -- -- -- -- -- - component destroyed -- -- -- -- -- - ')}, Render () {the console. The log (' -- -- -- -- -- - perform render function -- -- -- -- -- - ') return (< div > {this. State. The test} < / div >)}}) let open = true; window.addEventListener('click',()=>{ if(open){ ReactDOM.render( <Hi />, Document.body)}else{reactdom.render (<div> change component </div>, document.body)} open =! open })Copy the code

Column resolution, this time using click event replacementReactThe components of the

12) React in ES6

Class Hi extends React.Component {constructor(props){console.log(' initialize state') super(props); this.seting = { color : 'hello, ES6 syntax '}} componentWillMount(){console.log()} componentDidMount(){console.log()} componentWillUnmount(){componentWillUnmount(){ Console. log('render ') {console.log('render function ') return(<div>{this.setting. color}</div>)}}; ReactDOM.render( <Hi />, document.body )Copy the code

13) A code that lets you understand React completely

class Hi extends React.Component { constructor(props){ super(props) this.state = { color : 'red', fontSize : '40px'} console.log(' init state')} componentWillMount(){console.log(' hook function before component mounting ')} componentDidMount(){ Console. log(' componentWillUnmount ')} componentWillUnmount(){console.log(' component destruction ')} render(){console.log('render function ') return () <div style={this.state}> <p> React</p> </div>)}} reactdom.render (<Hi />, document.body)Copy the code

Read the article Ruan Yifeng react