search
HomeWeb Front-endJS TutorialDetailed explanation of the steps for component development in React

Detailed explanation of the steps for component development in React

This time I will bring you a detailed explanation of the steps for component development with React. What are the precautions for component development with React? The following is a practical case. Let’s take a look. .

Goal

Understand several reference points for component design:

  • Component unpacking principles

  • Component Inter-communication

  • Two-way binding

1. Component design

1.1 By presence or absenceState management Can be divided into Stateful components Stateless components

Illustration

Detailed explanation of the steps for component development in React-有无状态管理

1.1.1 Stateful Component, created in the form of React.Component

  • is used to manage application data. For example, in business, the data required for the homepage is:

    • Recommended categories

    • Recommended ads

    • Recommended products

Code example

class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      推荐分类列表:[],
      推荐广告列表:[],
      推荐商品列表:[]
      }
  }
  render() {
    return ...首页>
  }
}

1.1.2 Stateless components are mostly displayed in the form of functions. Try to use this form during development

This kind of component does not maintain state by itself, and data is transferred by attributes. Enter

Code sample

function Element(props) {
  let val = props.val
  return <p>组件 - ...</p>
}

1.2 Divide components into container componentsfunction##operation componentsdisplay componentsIllustration

##1.2.1 Container componentDetailed explanation of the steps for component development in React-按职能划分组件

This type of component itself is a stateful component, like a stage handle Everyone presents it, passes the data using

attributes

, and then the subcomponent returns the data using

event

like the product above Search business
  • Status includes: search keywords, sorting, product list
    • Sub-components include: search bar, list control bar , product list
    • Code example
class Container extends Component {
  constructor(props) {
    super(props)
    this.state = {
      搜索关键字: '手机壳',
      排序: '综合',
      商品列表: []
      }
  }
  render() {
    return (
      <p>
        
        
        
      </p>
    )
  }
}
1.2.1 Operation component

Processes interactive operations, such as search box,

user Register

Login, shopping cart, article editing, taking pictures, uploading

Search box in the diagram, receiving attributes

keywords generated new dataEvent Method to return container componentCode example

function SearchInput(props) {
  let 关键字 = props.关键字
  return (
    <p>
      <input>
    </p>
  )
}
1.2.1 Display component

This is more pure, only receiving

properties

Data, used to display the product list in the

diagram, receiving attributes

Product listCode example

function SearchInput(props) {
  let 商品列表 = props.商品列表
  return (
    <p>
      {商品列表.map((item, index) => (
        
      ))}
    </p>
  )
}
where

Product information

The component is also a
display component, split the component as much as possible2. Communication between components
is actually in a container component On the top, a

control component

and a

display componentillustration

we start writing Let’s take a lookDetailed explanation of the steps for component development in React

The first step: Write the input component

code

function InputView(props) {
  return (
    <p>
      <input>
    </p>
  )
}

Process the

onKeyDown

message and return it to the parent container

Second Step: Write the list display component

Code

function ListView(props) {
  return (
    <ol>
      {props.datas &&
        props.datas.map((item, index) => (
          <li>{item}</li>
        ))}
    </ol>
  )
}

map

Print the data list in a loop

The third step: Container component binding status and events

Code

class ContainerView extends Component {
  constructor(props) {
    super(props)
    this.state = {list: []}
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(e) {
    if (e.keyCode === 13) {
      const value = e.target.value
      e.target.value = ''
      this.setState((state, props) => {
        let list = state.list
        list.push(value)
        return {list}
      })
    }
  }
  render() {
    return (
      <p>
        <inputview></inputview>
        <listview></listview>
      </p>
    )
  }
}

e.keyCode === 13 表示一直监控到输入回车,开始更新状态

  • 动图效果

Detailed explanation of the steps for component development in React

  • codepen

https://codepen.io/ducafecat/...

3. Detailed explanation of the steps for component development in React

这个例子加入Detailed explanation of the steps for component development in React功能,这在表单操作中用的很频繁

图解说明

Detailed explanation of the steps for component development in React

还是用代码说明

3.1 第一步:输入组件

代码

class InputView extends Component {
  constructor(props) {
    super(props)
    this.form = props.form // 父容器 state.form
    this.sync = props.sync // 父容器 sync
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(e) {
    let name = e.target.attributes.name.value
    let value = e.target.value
    this.sync({name, value})
  }
  render() {
    return (
      
            
  •                    
  •         
  •                    
  •         
  •                    
  •       
    )   } }
  • props.form 是容器传入的表单数据,结构如下

{
  input: '',
  textarea: '',
  select: ''
}

按控件名称 key / val 结构

  • props.sync 是回传父容器的事件,相应代码如下

  handleChange(e) {
    let name = e.target.attributes.name.value
    let value = e.target.value
    this.sync({name, value})
  }

可以发现回传的是 {控件名, 控件值},这里是简写(键、值 名相同时可以写一个),完整格式是

{
  name: name,
  value: value
}

3.2 第二步:展示组件

代码

function ListView(props) {
  let form = props.form
  let list = []
  for (let key in form) {
    list.push({
      key,
      value: form[key]
    })
  }
  return (
    
          {list &&         list.map((item, index) => (           
  •             {item.key} - {item.value}           
  •         ))}     
  ) }

这里做展示就简单了,接收到属性 form 后,格式化成数组 list ,然后 map 打印

3.3 第三步:容器组件

代码

class ContainerView extends Component {
  constructor(props) {
    super(props)
    this.state = {form: {input: '', textarea: '', select: ''}}
    this.handleSync = this.handleSync.bind(this)
  }
  handleSync(item) {
    this.setState((prevState, props) => {
      let form = prevState.form
      form[item.name] = item.value
      return {form}
    })
  }
  render() {
    return (
      <p>
        <inputview></inputview>
        <listview></listview>
      </p>
    )
  }
}

handleSyncform[item.name] = item.value 动态更新 key / value 达到更新 state

  • 动图效果

  • codepen

https://codepen.io/ducafecat/...

建议

通过学习本章后,大家写具体功能代码前,可以先做下 UI组件架构设计

这个没有那么神秘,就是描述下有哪些组件、他们之间如何组装

如果大脑中抽象的不清楚,可以借助原型工具设计,自己能看懂就行,否则边写边设计容易乱掉

设计完成后,过几遍没啥问题了,再编写具体功能

代码

  • Detailed explanation of the steps for component development in Reactjs-example / 4-1-inputListView.js

  • Detailed explanation of the steps for component development in Reactjs-example / 4-2-formView.js

参考文

  • Lifting State Up

  • Thinking in React

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

JS中的JSON和Math使用案例分析

JS中使用接口步骤详解

The above is the detailed content of Detailed explanation of the steps for component development in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.