About React
Basic use of React
<div id="test"></div> <script type="text/javascript" src="../js/react.development.js"></script> <script type="text/javascript" src="../js/react-dom.development.js"></script> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel"> //babel must be declared // Create a virtual DOM element const vDom = <h1>Hello React</h1> // Never use quotation marks // Render the virtual DOM into the real DOM container of the page ReactDOM.render(vDom, document.getElementById('test')) </script>
Basic use of JSX
React uses JSX instead of regular JavaScript.
JSX is a JavaScript syntax extension that looks much like XML.
We don't have to use JSX, but it has the following advantages:
JSX executes faster because it is optimized after compiling into JavaScript code. It is type safe and errors can be found during compilation. Writing templates using JSX is easier and faster. For example:
var myDivElement = <div className="foo" />; ReactDOM.render(myDivElement, document.getElementById('example'));
<div id="test"></div> <div id="test2"></div> <script type="text/javascript" src="../js/react.development.js"></script> <script type="text/javascript" src="../js/react-dom.development.js"></script> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript"> // 1. Create virtual DOM /*Method 1: create a virtual DOM element object in pure JS (generally not used)*/ const msg = 'I Like You!' const myId = 'Atguigu' //First tag, second id tag attribute, third tag body content //React.createElement('h2', {id: myId}, hello) const vDOM1 = React.createElement('h2', {id: myId}, msg.toUpperCase()) // 2. Render to real page const domContainer = document.getElementById('test') // debugger ReactDOM.render(vDOM1, domContainer) </script> <script type="text/babel"> //babel must be declared const msg='I LIKE YOU' const myId='vue' // 1. Create virtual DOM /*Method 2: JSX creates a virtual DOM element object*/ const vDOM2 = <h3 id={myId.toUpperCase()}>{msg.toLowerCase()}</h3> // debugger // 2. Render to real page ReactDOM.render(vDOM2, document.getElementById('test2')) ReactDOM.render(vDom, domContainer) </script>
Three components of React (state,props,refs)
State component
React regards a component as a state machine. Through interaction with users, different states are realized, and then the UI is rendered to keep the user interface and data consistent.
In React, you only need to update the state of the component, and then Front end training The new state re renders the user interface (do not manipulate the DOM).
The following example creates an ES6 class with the name extended to React.Component, and uses this.state in the render() method to modify the current time.
Add a class constructor to initialize the state this.state. Class components should always use props to call the underlying constructor.
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( <div> <h1>Hello, world!</h1> <h2>Now it is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('example') );
Add lifecycle methods to classes
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <h2>Now it is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('example') );
props component
React regards a component as a state machine. Through interaction with users, different states are realized, and then the UI is rendered to keep the user interface and data consistent.
In React, you only need to update the state of the component, and then re render the user interface according to the new state (do not operate the DOM).
function HelloMessage(props) { return <h1>Hello {props.name}!</h1>; } const element = <HelloMessage name="Runoob"/>; ReactDOM.render( element, document.getElementById('example') );
Event handling
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // Binding here is necessary so that 'this' can be used in the callback function this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); } } ReactDOM.render( <Toggle />, document.getElementById('example') );
Modification of conditions
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } ReactDOM.render( // Attempt to modify isLoggedIn={true}: <Greeting isLoggedIn={false} />, document.getElementById('example') );
Declaration period
class Hello extends React.Component { constructor(props) { super(props); this.state = {opacity: 1.0}; } componentDidMount() { 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 () { return ( <div style={{opacity: this.state.opacity}}> Hello {this.props.name} </div> ); } } ReactDOM.render( <Hello name="world"/>, document.body );
React AJAX
The data of the React component can be obtained through Ajax in the componentDidMount method. When the data is obtained from the server, the data can be stored in state, and then the UI can be re rendered with this.setState method.
class UserGist extends React.Component { constructor(props) { super(props); this.state = {username: '', lastGistUrl: ''}; } componentDidMount() { this.serverRequest = $.get(this.props.source, function (result) { var lastGist = result[0]; this.setState({ username: lastGist.owner.login, lastGistUrl: lastGist.html_url }); }.bind(this)); } componentWillUnmount() { this.serverRequest.abort(); } render() { return ( <div> {this.state.username} User's latest Gist Share address: <a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a> </div> ); } } ReactDOM.render( <UserGist source="https://api.github.com/users/octocat/gists" />, document.getElementById('example') );
React Refs
React supports a very special attribute Ref, which you can use to bind to any component of render() output.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React example</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class MyComponent extends React.Component { handleClick() { // Get focus using native DOM API s this.refs.myInput.focus(); } render() { // After the component is inserted into the DOM, the ref attribute adds a reference of the component to this.refs return ( <div> <input type="text" ref="myInput" /> <input type="button" value="Click my input box to get focus" onClick={this.handleClick.bind(this)} /> </div> ); } } ReactDOM.render( <MyComponent />, document.getElementById('example') ); </script> </body> </html>
Original author: Y werewolf