You can understand it at a glance and simply understand react

Install using script tags or npm packages

Render Elements

js function to generate dom

Reactdom.render (element, bound and mounted to)

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

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.

Let's look at the following code first:

const element = <h1>Hello, world!</h1>;

This possibly strange looking tag syntax is neither string nor HTML.

It is called JSX, a syntax extension of JavaScript. We recommend using JSX to describe the user interface in React.

JSX is implemented inside JavaScript.

We know that elements are the smallest units of React applications, and JSX is used to declare the elements in React.

Different from the DOM elements of the browser, the elements in react are actually ordinary objects. React DOM can ensure that the data content of the browser DOM is consistent with the react elements.

To render the React elements to the root DOM node, we render them to the page by passing them all to the method of ReactDOM.render()

style
React Inline style is recommended. We can use camelCase Syntax to set inline style. React It is automatically added after the element number is specified px . The following example demonstrates h1 Element addition myStyle Inline style:

React example
var myStyle = {
    fontSize: 100,
    color: '#FF0000'
};
ReactDOM.render(
    <h1 style = {myStyle}>Rookie tutorial</h1>,
    document.getElementById('example')
);

Give it a try »
notes
 Notes need to be written in curly braces. Examples are as follows:

React example
ReactDOM.render(
    <div>
    <h1>Rookie tutorial</h1>
    {/*notes...*/}
     </div>,
    document.getElementById('example')
);

Give it a try »
array
JSX It is allowed to insert an array into the template, and the array will automatically expand all members:

React example
var arr = [
  <h1>Rookie tutorial</h1>,
  <h2>Learning is not only technology, but also a dream!</h2>,
];
ReactDOM.render(
  <div>{arr}</div>,
  document.getElementById('example')
);

assembly

A component is defined using a function:

function HelloMessage(props) {
    return <h1>Hello World!</h1>;
}
use ES6 class To define a component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello World!</h1>;
  }
}

Components can be combined

function Name(props) {
    return <h1>Website name:{props.name}</h1>;
}
function Url(props) {
    return <h1>Website address:{props.url}</h1>;
}
function Nickname(props) {
    return <h1>Website nickname:{props.nickname}</h1>;
}
function App() {
    return (
    <div>
        <Name name="Rookie tutorial" />
        <Url url="http://www.runoob.com" />
        <Nickname nickname="Runoob" />
    </div>
    );
}
 
ReactDOM.render(
     <App />,
    document.getElementById('example')
);

Use state to save the state. props receives attribute parameters, the parent component passes parameters, and the child component modifies the parent component value directly. setState modify state value

Default Props defaultProps

You can set the default value for props through the defaultProps property of the component class,

class HelloMessage extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
 
HelloMessage.defaultProps = {
  name: 'Runoob'
};
 
const element = <HelloMessage/>;
 
ReactDOM.render(
  element,
  document.getElementById('example')
);

Props validate propTypes

var title = "Rookie tutorial";
// var title = 123;
class MyTitle extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.title}</h1>
    );
  }
}
 
MyTitle.propTypes = {
  title: PropTypes.string
};
ReactDOM.render(
    <MyTitle title={title} />,
    document.getElementById('example')
);

The event handling of the React element is similar to that of the DOM element. But there is one grammatical difference:

  • The name of the React event binding attribute is written in Hump rather than lowercase.
  • If you use JSX syntax, you need to pass in a function as an event handler instead of a string (the way DOM elements are written)
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')
);

With parameters
class Popper extends React.Component{
    constructor(){
        super();
        this.state = {name:'Hello world!'};
    }
    
    preventPop(name, e){    //The event object e should be placed last
        e.preventDefault();
        alert(name);
    }
    
    render(){
        return (
            <div>
                <p>hello</p>
                {/* Pass parameters through the bind() method. */}
                <a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
            </div>
        );
    }
}

Conditional rendering uses expressions to determine display elements

React component API

In this chapter, we will discuss the React component API. We will explain the following 7 methods:

  • Setting state: setState
  • Replacement status: replaceState
  • Setting properties: setProps
  • Replacement attribute: replaceProps
  • Forced update: forceUpdate
  • Get DOM node: findDOMNode
  • Judge component mounting status: isMounted

React component lifecycle

In this chapter, we will discuss the lifecycle of React components.

The life cycle of a component can be divided into three states:

  • Mounting: real DOM inserted
  • Updating: being re rendered
  • Unmounting: removed from real DOM

Life cycle methods include:

  • componentWillMount is invoked before rendering and the client is also on the server side.
  • componentDidMount: call after the first rendering, only on the client side. After that, the component has generated the corresponding DOM structure, which can be accessed through this.getDOMNode(). If you want to work with other JavaScript frameworks, you can invoke setTimeout, setInterval, or send AJAX requests in this method (to prevent asynchronous operations blocking UI).
  • componentWillReceiveProps is called when the component receives a new prop (Updated). This method will not be called when initializing render.
  • shouldComponentUpdate returns a Boolean value. Called when the component receives a new props or state. Not called during initialization or when using forceUpdate.
    It can be used when you confirm that you do not need to update the component.
  • componentWillUpdate is called when the component receives a new props or state but has not yet render ed. Is not called during initialization.
  • componentDidUpdate is called immediately after the component completes updating. Is not called during initialization.
  • componentWillUnmount is called immediately before the component is removed from the DOM.
class Button extends React.Component {
  constructor(props) {
      super(props);
      this.state = {data: 0};
      this.setNewNumber = this.setNewNumber.bind(this);
  }
  
  setNewNumber() {
    this.setState({data: this.state.data + 1})
  }
  render() {
      return (
         <div>
            <button onClick = {this.setNewNumber}>INCREMENT</button>
            <Content myNumber = {this.state.data}></Content>
         </div>
      );
    }
}
 
 
class Content extends React.Component {
  componentWillMount() {
      console.log('Component WILL MOUNT!')
  }
  componentDidMount() {
       console.log('Component DID MOUNT!')
  }
  componentWillReceiveProps(newProps) {
        console.log('Component WILL RECEIVE PROPS!')
  }
  shouldComponentUpdate(newProps, newState) {
        return true;
  }
  componentWillUpdate(nextProps, nextState) {
        console.log('Component WILL UPDATE!');
  }
  componentDidUpdate(prevProps, prevState) {
        console.log('Component DID UPDATE!')
  }
  componentWillUnmount() {
         console.log('Component WILL UNMOUNT!')
  }
 
    render() {
      return (
        <div>
          <h3>{this.props.myNumber}</h3>
        </div>
      );
    }
}
ReactDOM.render(
   <div>
      <Button />
   </div>,
  document.getElementById('example')
);

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.

When loading data asynchronously, use componentWillUnmount to cancel outstanding requests before component unloading.

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 forms and events

In this chapter, we will discuss how to use forms in React.

HTML form elements are different from other DOM elements in React because form elements are born to retain some internal state.

In HTML, form elements such as, and maintain their state and update according to user input. However, in React, the variable state is usually saved in the state attribute of the component, and can only be updated with the setState() method.

In the example, we set the input value of the input box value = {this.state.data}. We can update the state when the value of the input box changes. We can use the onChange event to listen for changes in input and modify the state.

class HelloMessage extends React.Component {
  constructor(props) {
      super(props);
      this.state = {value: 'Hello Runoob!'};
      this.handleChange = this.handleChange.bind(this);
  }
 
  handleChange(event) {
    this.setState({value: event.target.value});
  }
  render() {
    var value = this.state.value;
    return <div>
            <input type="text" value={value} onChange={this.handleChange} /> 
            <h4>{value}</h4>
           </div>;
  }
}
ReactDOM.render(
  <HelloMessage />,
  document.getElementById('example')
);

React Refs

React supports a very special attribute Ref, which you can use to bind to any component of render() output.

This special property allows you to refer to the corresponding backing instance returned by render(). This ensures that you always get the right instance at any time.

Bind a ref attribute to the return value of render:

<input ref="myInput" />

In other codes, obtain the support instance through this.refs:

var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
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')
);

Tags: Javascript React

Posted on Sat, 18 Sep 2021 03:08:44 -0400 by cityguru