react study notes

One, the basic format

1. The files that need to be imported

        <!-- react core library -->
	<script src="build/react.js"></script>
	<!-- Provides some functionality related to the DOM -->
	<script src="build/react-dom.js"></script>
	<!-- Convert JSX syntax to javascript -->
	<script src="build/browser.min.js"></script>

2, DOM node

	<!-- The template content rendered by react will be inserted into this node as a container -->
	<div id="container"></div>

3. JSX syntax

Using JSX in react development is not compatible with javascript. Where JSX is used, type:text/babel should be set

<script type="text/babel">
	// write react code here
</script>

JSX is not a new language, it is a syntax (syntactic sugar)

1. jsx must be run with the help of the React environment
2. The jsx tag is actually an html tag, but when we write these tags in javascript, we can write them like XML without using "" brackets.

3. It allows us to see the dom structure of the component more intuitively, which cannot be run directly on the browser, and will eventually be converted into javascript code.

js writing:

ReactDOM.render(
	React.createElement("h1",null,"你好,react"),
	document.getElementById("container")
)

JSX writing:

var text="aaa";
	ReactDOM.render(
		<h1>{text}</h1>,
		document.getElementById("container")
	)
To run javascript code in JSX, enclose {expression} with {}

4, ReactDOM.render()

The most basic method of React is to convert the template into HTML language, render the DOM, and insert it into the specified DOM node.

ReactDOM.render(
<h1>Hello, react</h1>,
document.getElementById("container")
);

3 parameters
The first: the rendering content of the template (HTML form)
The second: the DOM node that this template needs to insert (in this program, the div node with the ID as container)
The third: the callback after rendering, generally not needed

Second, define components

1. Component format

1> The component class created in react starts with a capital letter and is named in camel case;

2> Use the React.createClass method to create a component class in React;

3> Core code: Each component class must implement its own render method. The component template that outputs the definition number;

4> Note: Each component class can only contain one top-level label;

	var HelloMessage = React.createClass({
		render:function(){
			return <h1>Hello react</h1>
		}
	});
		ReactDOM.render(
			// Inserting <HelloMessage /> in the template will automatically generate an instance
			<HelloMessage />,
			document.getElementById("container")
		)

2. Component style

1, Restrained Style
2, Object Style

3, the selector style

There is a difference in the writing format of setting styles in react and html5 in react and html5

1, html5 ends with ';'; react ends with ','.

2. The key and value in html5 are not quoted; in react, it is a javascript object, and the name of the key cannot appear "-", and it needs to be named in camel case. If value is a string, quotes are required.

3. In html5, if the value is a number, it needs to have a unit; react does not need a unit.

<style media="screen">
		.pStyle{
			font-size: 20px;
		}
</style>

In react, if you want to use the selector style to set the component style, the property name cannot use class, you need to use className instead. Similarly, use htmlFor instead of for


// Create and set h1 style object
var HStyle = {
	backgroundColor:"green",
	color:"red"
}

var ShowMessage = React.createClass({
	render:function(){
		return (
			// Object inside, syntax outside, no unit
			<div style={{backgroundColor:"yellow",borderWidth:5,borderColor:"blue",borderStyle:"solid"}}>
					<h1 style={HStyle}>{this.props.firstRow}</h1>
					<p className="pStyle">{this.props.secondRow}</p>
			</div>
		)
	}
});

ReactDOM.render(
	<ShowMessage firstRow='你好' secondRow='react'/>,
	document.getElementById("container")
);

3. Composite components.

// define WebName
var WebName = React.createClass({
	render:function(){
		return <h1>Baidu</h1>;
	}
});

// Define the WebLink component
var WebLink = React.createClass({
	render:function(){
		return<a href="http://www.baidu.com">baidu</a>
	}
});

var WebShow= React.createClass({
	render:function() {
		return(
			<div>
				<WebName />
				<WebLink />
			</div>
		);
	}
});

ReactDOM.render(
	<WebShow />,
	document.getElementById("container")
)
</script>

Three, component properties

1,props

Props are the properties of the component itself, which are generally used in the inner and outer components of absconding and are responsible for passing information (usually the parent component to the child component).

Note: The properties in the props object correspond to the properties of the component one by one, and uyao directly modifies the value of the properties in the props.

        // define WebName
	var WebName=React.createClass({
		render:function(){
			return <h1>{this.props.webname}</h1>
		}
	})
	// define WebLink
	var WebLink=React.createClass({
		render:function(){
			return <a href={this.props.weblink}>{this.props.weblink}</a>
		}
	})
	//Define WebShow
	var WebShow=React.createClass({
		render:function(){
			return(
				<div>
					<WebName webname={this.props.wname}/>
					<WebLink weblink={this.props.wlink}/>
				</div>
			)
		}
	})
	
	ReactDOM.render(
		<WebShow wname="baidu" wlink="www.baidu.com" />,
		document.getElementById("container")
	)

2,...this.props

The syntactic sugar provided by props can copy all the properties of the parent component to the child component.

var Link = React.createClass({
		render:function(){
			return <a {...this.props}>{this.props.name}</a>
		}
	});
	
	ReactDOM.render(
		<link href="http://www.baidu.com" name="中文" />,
		document.getElementById("container")
	);

3,this.props.children

children is an exception, not all child nodes of the display component corresponding to the properties of the component

var ListComponent = React.createClass({
		render:function(){
			return(
				<ul>
				{
				/* The number and content of list items are uncertain, and can only be determined when the template is created
					Use this.props.children to get the list item content that needs to be displayed from the parent component

					After getting the content of the list item, you need to traverse the children and set them item by item
					Using React.Childern.map method
					Return value: Array object. The elements in the array here are li

					*/
					React.Children.map(this.props.children,function(child){
						// child is the child node of the parent component obtained by traversal
						return <li>{child}</li>
					})

				}
				</ul>
			);
		}
	});
	ReactDOM.render(
(
		<ListComponent>
		<h1>This is the name</h1>
		<a>www.baidu.com</a>
		</ListComponent>

	),
	document.getElementById("container")
	)

4, property validation propTypes

Attributes of the component class to verify whether the attributes of the component instance are compound requirements.

var ShowTitle = React.createClass({
	propTypes:
		//title data type must be string type
		title:React.PropTypes.string.isRequired
	},
	render:function(){
		return <h1>{this.props.title}</h1>
	}
})

ReactDOM.render(
	<ShowTitle title="a"/>,
	document.getElementById("container")
)

5,getDefaultProps

Set default values ​​for component properties

var MyTitle=React.createClass({
	getDefaultProps:function (){
		return{
			title:"wyy"
		}
	},
	render:function(){
		return <h1>{this.props.title}</h1>
	}
})
ReactDOM.render(
	<MyTitle />,
	document.getElementById("container")
)

Fourth, the form

1. Event handling

The event name in react, the first letter is lowercase, camel case.

	var MyButton=React.createClass({
		handleClick(){
			alert("hehe")
		},
		render(){
			return<button onClick={this.handleClick}>{this.props.buttonTitle}</button>
		}
	})
	ReactDOM.render(
		<MyButton buttonTitle="anniu"/>,
		document.getElementById("container")
	)

2, state state

Like props, they are all properties of the component itself

var CheckButton=React.createClass({
		//define the initial state
		getInitialState () {
			return {
				//Properties set in this object will be stored in state
				//The default state is not selected
					isCheck:false
			}
		},
		//define the method of event binding
		handleChange(){
			//Modify the state value and read the set state value through this.state
			this.setState({
				isCheck:!this.state.isCheck
			})
		},
		render(){
			//Set the displayed text according to the status value
			//If()else{} cannot be used directly in JSX, use the ternary operator
			var text=this.state.isCheck?"Checked":"Unchecked";
			return(
				<div>
				<input type="checkbox" onChange={this.handleChange} />
				{text}
				</div>
			)
		}
}	)
	ReactDOM.render(
		<CheckButton />,
		document.getElementById("container")
	)

When the state changes, the component also calls the render method inside the component

Define a component that is displayed in real time when the user types:

var InputText=React.createClass({
		getInitialState () {
			return{
				value:"Please enter"
			};
		},
		toChange(event){
			//Read the value entered by the user through event.target.value
			this.setState({
				value: event.target.value
			});
		},
		render(){
			var value=this.state.value;
			return(
				<div>
					<input type="text" value={value} onChange={this.toChange}/>
					<p>{value}</p>
				</div>
			)
		}
	})
	ReactDOM.render(
		<InputText />,
		document.getElementById("container")
	)

Five, life cycle

  1, three states:
    mounting: component mounted, real DOM inserted
    updating: component updated, being re-rendered
    unmountong: component removed, removed real DOM


   2, four stages

    Create, instantiate, update, destroy

Six, life cycle related methods

1. Mounting related methods:
      (1) The componentWillMount
      component is about to be mounted.
      Executed before render, but only once, even if the component is repeatedly rendered multiple times, or the state of the component is changed
      (2) The componentDidMount
      component has been mounted. Executed after render, the same component is only executed once for repeated rendering

2, update related methods
      (1) componentWillReceiveProps(object nextProps)
      is called before the loaded component receives new props, note that it will not be executed when the component is initialized and rendered
      (2) shouldComponentUpdate( object nextProps, object nextState)
      is called when the component judges whether to re-render. This interface is actually called immediately when the component receives new props or new state, and then the component will be called through       (
      3) componentWillUpdate(obkect nextProps, object nextState)
Update
      (4) componentDidUpdate(object prevPorps, object prevState) The
      component has been updated

3, and the component removes related methods.
      componentWillUnmount
      fires just before the component is to be removed. This method can be used to perform some necessary cleanup components will be removed

4. Related to props and state in the life cycle:
      (1) getDefaultProps sets the default value of the props property
      (2) getInitialState sets the initial value of the state property

5. Introduction to each stage of the life cycle

var Demo=React.createClass({
    /* First, create stage
    process:
      Only call the getDefaultProps method
    */
    getDefaultProps(){
      console.log("getDefaultProps");
      return {};
    },
    /*
      Second, the instantiation stage
      process:
        getInitialState
        componentWillMount
        render
        componentDidMount
    */
    getInitialState () {
      console.log("getInitialState");
      return {};
    },
    componentWillMount(){
      console.log("componentWillMount");
    },
    render(){
      // used to render and return a virtual DOM
      console.log("render: used to render and return a virtual DOM");
      return <div>Lifecycle</div>;
    },
    componentDidMount(){
      /*
      called after render
      In this method, react will use the virtual DOM object returned by the render method to create the real DOM structure
      DOM nodes can be read in this method
      */
      console.log("componentDidMount");
    },
    /*
      Third, the update process
        process:
        componentWillReceiveProps
        If the return value of shouldComponentUpdate is false, then the last three methods are not executed
        componentWillUpdate
        render
        componentDidUpdate
    */
    componentWillReceiveProps(){
      console.log("componentWillReceiveProps");
    },
    shouldComponentUpdate(){
      console.log("shouldComponentUpdate");
      return true
    },
    componentWillUpdate(){
      console.log("componentWillUpdate");
    },
    componentDidUpdate(){
      console.log("componentDidUpdate");
    },
    /*
      Fourth, the destruction stage
      process:
        componentWillUnmount
    */
    componentWillUnmount(){
      console.log("componentWillUnmount");

    }
  })

  //Create and load the component for the first time
  ReactDOM.render(
    <Demo />,
    document.getElementById("container")
  );

  //re-render the component
  ReactDOM.render(
    <Demo />,
    document.getElementById("container")
  )

  // remove the component
ReactDOM.unmountComponentAtNode(document.getElementById("container"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325473223&siteId=291194637