编程知识 cdmana.com

React (3) react components

Preface

React Framework is a component framework , In order to be suitable for the development of large projects ,React Divide the project into components , And frequently pass data between components . It can be said that if you want to learn well React Use of framework , Need to be able to operate components flexibly . This article focuses on React The way components are written , And give the data and event processing rules in the component .

Be careful :React 16.x In the previous version , Creating components can use React.createClass() Method to implement , But from React 16 Version start , The method is completely abandoned , Start using it all ES6 Medium class Keywords to create components . In the learning process , Don't try again React.createClass() The method .


One 、 Use ES6 Of class Keyword creation component

React Use ES6 Of class The syntax format of the keyword creation component is as follows .

class  Component name  extends React.Component{
  render(){
    return (
       //JSX Elements 
    )
  }
} 

The above format has the following format requirements when writing :

  • The first letter of the component name must be capitalized .
  • Must have render() function .
example 1: Create a file called App The components of , This component shows a h2 Title and with 3 An unordered list of list items .
class App extends React.Component{
  render(){
    return (
      <React.Fragment>
        <h2> The three frameworks of front end development </h2>
        <ul>
          <li>React</li>
          <li>Vue.js</li>
          <li>Angular</li>
        </ul>
      </React.Fragment>
    )
  }
}
ReactDOM.render(
  <App></App>,
  document.querySelector("#app")
) 

As you can see from the above code , Component name App Can appear in ReactDOM.render() In the first argument of the function , It can be the format of a tag pair (<App></App>), It can also be a single label format (<App />).

It can be seen that , There are two React Very common properties in components :

  • React.Component: All custom components inherit React.Component.
  • React.Fragment: As the only root node of a custom component , And in DOM No rendering in structure .

To simplify the calling of the above two properties , We can use ES6 The format of object deconstruction is declared at the beginning of the project :

const {Component,Fragment} = React; 

In this way, we will lead you to create a component .

example 2: Create a file called App The components of , This component traverses the array to form 5 A hyperlink .
const {Component,Fragment}=React;
let linkText=[" Baidu "," tencent "," Sina "," NetEase "," Google "];
let linkUrl=[
  "https://www.baidu.com",
  "https://www.qq.com",
  "https://www.sina.com.cn",
  "https://www.163.com",
  "https://www.google.com"
];
class App extends React.Component{
  render(){
    return (
      <React.Fragment>
        {
          linkText.map((item,index)=>{
            return <a href={linkUrl[index]} key={index}>{item}</a>
          })
        }
      </React.Fragment>
    )
  }
}
ReactDOM.render(
  <App></App>,
  document.querySelector("#app")
); 

Two 、 Set the state area for the component

according to ES6 Grammatical rules , Use class Defined React A component is essentially a class ,ES6 Allows you to set a constructor for a class inside a class , Inside this constructor, it can be used for the entire React Component set state area (state). Have studied Vue.js The partners of the framework can understand it as Vue The data area of the instance ( namely data part ).

The syntax format is as follows .

class  Component name  extends React.Component{
  constructor(props){
    super(props);
    this.state={
      // Declare state area data 
    }
  }
} 
example 3: Components Student There are two data in the state area of , title title And student information info, Use the data in the status area to generate a table showing the student information in the page .
const {Component,Fragment}=React;
class Student extends Component{
  constructor(props){
    super(props);
    this.state={
      title:' Front end of Xiaohai 2059 The list of students in the second term ',
      info:[
        {name:' Zhang San ', sex:' male ', age:24, phone:'159xxxxxxxx'},
        {name:' Li Si ', sex:' Woman ', age:22, phone:'139xxxxxxxx'},
        {name:' Wang Wu ', sex:' male ', age:25, phone:'157xxxxxxxx'}
      ]
    }
  }
  render(){
    return (
      <Fragment>
        <h2>{this.state.title}</h2> <hr/>
        <table>
          <thead>
            <tr>
              <th> full name </th>  <th> Gender </th>  <th> Age </th>  <th> contact number </th>
            </tr>
          </thead>
          <tbody>
            {
              this.state.info.map((stud,index)=>{
                return (
                  <tr key={index}>
                    <td>{stud.name}</td>
                    <td>{stud.sex}</td>
                    <td>{stud.age}</td>
                    <td>{stud.phone}</td>
                  <tr>
                )
              })
            }
          </tbody>
        </table>
      </Fragment>
    )
  }
}
ReactDOM.render(
    <Student></Student>,
document.querySelector("#app")
); 

As you can see from the above code , stay JSX Reference in grammatical structure state The data in the area should use this.state To achieve .

Let's think about a question : there this What do you point to ?

class Student extends Component {
  constructor(props){
    super(props);
    this.state={
      // Definition state Area data 
    }
  }
  render(){
    console.log(this);
    return (
      //JSX Grammatical structure 
    );
  }
} 

The above code is in render() Function using console.log() The structure will this The content of the output to the console , The final output is shown in the figure below .
 Insert picture description here
As you can see from this picture , In the component this The keyword always points to the component itself , And through this.state Call the data in the component state area .

So how to modify components state What about the data in the area ? I need to use this.setState() Method to implement , The format is as follows .

this.setState({
   Data name : Value 
}) 

Let's first explain how to bind events to elements in a component , Then modify it when the event is triggered state Data in the zone .

3、 ... and 、 Binding events for elements in a component

stay React in , Generally, the method of element attribute is used to bind the event for it . The event type name uses on- start , The following event words are capitalized .

  • Click events :onClick
  • Mouse over event onMouseOver
  • Mouse away from event onMouseOut
  • Get focus event :onFocus
  • Release Focus Events :onBlur
example 4: establish Exam Components . There's a button in the page , Click the button to change state In the data area is called frame Data value of .
const {Component,Fragment}=React;
class Exam extends Component{
  constructor(props){
    super(props);
    this.state={
      frame:'Vue.js'
    }
  }
  changeData(){
    this.setState({
      frame:'React'
    })
  }
  render(){
    return (
      <Fragment>
        <button onClick={this.changeData.bind(this)}> Changing data </button>
        <p> Hello ,{this.state.frame}</p>
      </Fragment>
    )
  }
}
ReactDOM.render(
  <Exam></Exam>,
  document.querySelector("#app")
); 

We observe carefully for button The button binds the sentence of the click event :

<button onClick={this.changeData.bind(this)}> Changing data </button> 

The essence of the sentence is to define a changeData() Function of , Let this function be executed when the button click event is triggered . however , In the function this The keyword doesn't point to the component itself . In order to make the function internal this Just think about the component itself , Must be in JSX Syntax function is used when calling functions bind(this) To guarantee this The direction of a keyword in a function .

If you can't use this keyword , Then you can call a function without using bind(this) 了 .

example 5: Create components Box. There is a rectangular container in the page , Let the mouse change the background color as it passes by (#ff5857), Restore the original background color when the mouse leaves (#3385ff).
const {Component,Fragment}=React;
class Box extends Component{
  constructor(props){
    super(props);
    this.state={
      bgc:'#ff5857'
    }
  }
  mouseOver(){
    this.setState({
      bgc:'#3385ff'
    })
  }
  mouseOut(){
    this.setState({
      bgc:'#ff5857'
    })
  }
  render(){
    return (
      <Fragment>
        <div className="box"
             style={{backgroundColor:this.state.bgc}}
             onMouseOver={this.mouseOver.bind(this)}
             onMouseOut={this.mouseOut.bind(this)}>
        </div>
      </Fragment>
    )
  }
}
ReactDOM.render(
    <Box></Box>,
    document.querySelector("#app")
); 

In the above code div, Class name box Responsible for setting the width and height of the container ,style Property is responsible for setting the background color , And the background color uses a state It's called bgc To set . When the mouse passes through this container, use this.setState() Method change bgc The values for #3385ff; Use when the mouse leaves the container this.setState() Method change bgc The values for #ff5857.

Four 、 Make sure that... Is in the component method this Point to the component itself

In the previous example, we use bind(this) To ensure that the method in the component is internal this Pointing to the component itself . This section summarizes other implementation methods .

1、 Call methods with bind(this) To change the inside of the method this The direction of .

<button onClick={this.btnClick.bind(this)}> Submit </button> 

2、 Register methods in constructors .

You can also use this method in the constructor bind(this) Register again , In this way, you don't need to change when calling this Of points to .

constructor(props){
   super(props);
   this.state={ // Definition state Area data  };
   this.btnClick=this.btnClick.bind(this);      // Re register the method in the constructor 
}
<button onClick={this.btnClick()}> Submit </button> 

3、 Use arrow functions when calling methods .

You can also use the arrow function directly when calling a method , This can also solve the internal problem this Direction problem of .

<button onClick={()=>this.btnClick()}> Submit </button> 

The above three methods can be used to call the event function , The students can give an example 3 Or example 4 Change the way of calling methods on the basis of , Demonstrate the feasibility of the above method .


summary

This article is about React The third article in the series , Mainly for you to explain React The way components are written . At the same time, it also explains the use of component state area 、 Binding events for component elements, etc . Tomorrow will be a systematic explanation for you React Data transfer between components .

About author

Front end of Xiaohai , have 18 year Web Project development and background training experience , In the front-end field, he has written systematic training materials , Yes Vue.js、 Wechat applet development 、uniApp、React I have deep attainments in the field of full stack development . To stay in Segmentfault, Hope to get to know more Web Colleagues in the field of development , take Web Develop and popularize vigorously . At the same time, we are willing to conduct in-depth technical research and business cooperation with you .

版权声明
本文为[Xiaohai front end]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225114149254W.html

Scroll to Top