React Build a to-do list
create by db on 2019-3-10 16:28:10
Recently revised in 2019-4-1 17:06:13
Hello friends, if you think this article is good, please give a thumbs up or a star, your thumbs up and star are my motivation! Making the address
As a front-end rookie, the purpose of this article is to record their own learning experience, if there is any deficiency, please give me more advice, thank you.
preface
I hear and I fogorget.
I see and I remember.
I do and I understand.
React has been used to build a to-do list. This article is for the record.
- Note: This project is built based on the React 17.0.1 framework
If you are not familiar with the React project, please refer to:
- The React website
The body of the
1. Build React Project:
1. Install node and scaffolding
First you need to install Node >= 8.10 and NPM >= 5.6 on your machine. Node. Js official address is: https://nodejs.org/en/download/, download the corresponding version.
After installing Node, open CMD as administrator, and typenode -v
Press Enter to view the Node version number. If the version number is displayed, the installation is successful.
npx create-react-app my-app
Scaffolding installation:
npm install create-react-app -g
After installing node, open CMD as the administrator, type create-react-app -v, and press Enter to check the node version number. If the version number is displayed, the node is successfully installed.
Create a new project
Go to the folder you need to create in the project and open the command line.
npx create-react-app react-todolist
Finally, the following code appears
We suggest that you begin by typing:
cd react-todolist
yarn start
Happy hacking!
Copy the code
The initialization is successful and the project is set up.
3. Go to your project folder
With the project set up, you can now access the project folder.
Enter the following command and press Enter to enter the new project.
cd react-todolist
4. Start the project
With all the environment dependencies installed, let’s test out our new VUE project.
Type the following command and press Enter to start the project
yarn start
The default browser address is http://localhost:3000, as shown below:
Compiled successfully!
You can now view react-todolist in the browser.
Local: http://localhost:3000
On Your Network: http://xxx.xxx.xxx.xxx:3000
Note that the development build is not optimized.
To create a production build, use yarn build.
Copy the code
Open http://localhost:3000 in your browser and see your project
Ii. Overview of project structure
Once the scaffold has generated the catalog, it needs to have some basic knowledge of the catalog. Let’s take a look at how the React scaffolding generates directories and files.
Note: Different versions may cause different directory files. My own scaffolding version is: 4.0.3. To query your version number, enter the following code in the terminal:
create-react-app -V
│ - gitignore// A.gitignore file is required in a Git project. This file is used to tell Git which files do not need to be added to version management. Android VIRTUAL machine files dex and some configuration files containing passwords, etc. The contents of this file are rules that Git uses to decide whether to add a file to version control│ - filename. TXT │ - package. The json// Defines the various modules needed for the project, as well as the project configuration information (such as name, version, license, and other metadata). Based on this configuration file, the NPM install command automatically downloads the required modules, that is, the runtime and development environment required to configure the project. No changes are required at this time.│ - README. Md// readme.md :(the readme.md file is a starter manual for a project. It describes what the project will look like, what the environment will be, what skills will be available, and so on.│ - yarn. The lock// This file is the version number of the lock installation. You need to upload it to Git to ensure that other people's yarn dependencies are consistent.
│---node_modules // The react project contains some of the components that will be used by install
│---public // This folder is all public files used in some projects.│ - the favicon. Ico// Site or project icon, usually displayed in the upper left corner of the browser.│ - index. HTML// The React startup page is suitable for single-page application development, so for now only one index.html page is included, and this is also the entry page for the React project│ - logo192. PNG// Static image│ - logo512. PNG │ - manifest. The json// Mobile configuration file.│ - robots. TXT// Tell crawlers not to crawl pages. It only serves as a warning. Nothing of substance.└ ─ SRC// Contains some of our own use of js files, CSS files, img files, etc. Index.html is aligned with index.js by default. Index.js is our entry js, which corresponds to index.html│ - App. CSS// The component's CSS│ - App. Js// equivalent to a method module, also a simple modular programming. Also called a component.│ - App. Test. Js │ - index. The CSS// the CSS file in index.js│ - index. Js// Project entry file│ - logo. SVG │ - reportWebVitals. Js// Google's new library on browser performance optimization. (New file)│ - setupTests. Js// Unit test file for index.js
Copy the code
Start implementing ToDoList
With the React project structure covered, we are ready to implement the ToDoList project.
Create the ToDoList component
We can rename app. CSS file in/SRC to todolist. CSS, app. js file to todolist. js, introduce React and useState, rename their App methods to ToDoList, and delete unnecessary contents as follows:
import './ToDoList.css'
// Introduce React and useState
import React, { useState } from 'react'
function ToDoList() {
return (
<div className="App">
<h1>To Do List</h1>
</div>)}export default ToDoList
Copy the code
2. Introduce the ToDoList component
In the index.js file of/SRC, change the original registered App to ToDoList, as follows:
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import ToDoList from './ToDoList'
import reportWebVitals from './reportWebVitals'
ReactDOM.render(
<React.StrictMode>
<ToDoList />
</React.StrictMode>.document.getElementById('root'))// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()
Copy the code
OK, with the above two steps done, our project runs like this:
Create and render the list
Next, we create an array of items in the ToDoList function and the function Hook — setItems to update items. For the use of hooks, see the Hook Overview.
Then declare a list rendering function component ItemList, using map to implement the list loop, as follows:
// To-do list component
function ItemList(props) {
// Use map to traverse the incoming array and return the rendered list
const ItemLists = props.items.map((item, index) = > (
// Elements in the map() method require a key attribute.
<li key={item.id}>
{item.title}
<button>complete</button>
</li>
))
return ItemLists
}
function ToDoList() {
// Initialize the to-do list array
const [items, setItems] = useState([
{
id: 1.title: 'eat'}, {id: 2.title: 'sleep'}, {id: 3.title: 'Beat the beans',}])return (
<div className="App">
<h1>To Do List</h1>{/* To-do list */}<ul>{/* Pass the to-do list array into the component */}<ItemList items={items}></ItemList>
</ul>
</div>)}export default ToDoList
Copy the code
The rendered result looks like this:
Note:
- Key helps React identify which elements have changed, such as being added or removed. So you should give each element in the array a definite identity. An element’s key should ideally be a unique string that the element has in the list. In general, we use the id in the data as the element’s key:. For more details, see why keys are necessary
4. Bind the delete event
Next we use the button binding to delete the event
<button onClick={()= >ClickDelete (index)} ></button>
Copy the code
Here we add an onClick method called clickDelete that takes an array subscript index (numeric type).
We then define the clickDelete event in the component ItemList, and because we want to change the items array of the parent element, we fire the parent component’s deleteItem event
// Click Finish to trigger the parent component method
function clickDelete(index) {
props.deleteItem(index)
}
Copy the code
Next we give the parent ToDoList binding the deletion trigger event deleteItem to remove the corresponding item from the list when it is triggered.
<ItemList deleteItem="{deleteItem}" items="{items}"></ItemList>
Copy the code
DeleteItem removes the triggered items from the array and reassigns the array.
// Complete the to-do list
function deleteItem(index) {
items.splice(index, 1)
setItems([...items])
}
Copy the code
Note:
To use JSX syntax you need to pass in a function as an event handler, not a string.
Since we need to pass out the index argument, we can use the arrow function in the callback to pass in the parameter, and this ensures that handleClick’s this is bound.
5. Use the input field to add new items
So far we’ve been using ready-made lists. Next we’ll use the input field to dynamically add entries to the list.
The list rendering component is the function component we use, and then we use the class component to implement the new to-do component.
// Add the charge form component
class ItemForm extends React.Component {
constructor(props) {
super(props)
this.state = { value: ' ' }
// This binding is necessary in order to use 'this' in callbacks
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)}// Input box content changes, update state
handleChange(event) {
this.setState({ value: event.target.value })
}
// Click the submit button, save the option, please enter the content blank
handleSubmit(event) {
event.preventDefault()
if (!this.state.value) {
return
}
this.props.addNewItem(this.state.value)
this.setState({ value: ' '})}render() {
return (
<form onSubmit={this.handleSubmit}>
<label>To do:<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>)}}Copy the code
We then import this component in the ToDoList component and bind the add event
{
/* Add a list */};<ItemForm addNewItem={addNewItem}></ItemForm>
Copy the code
In the ToDoList component, we declare a variable id that defaults to 4. After entering the content in the input box, click the “Add” button to push a content in the array items, including ID and title. Then the ID increases and the array is updated.
// Initialize the ID
const [itemId, setItemId] = useState(4)
// Add todo
function addNewItem(data) {
let obj = {
id: itemId,
title: data,
}
items.push(obj)
setItemId(itemId + 1)
setItems(items)
}
Copy the code
conclusion
With this, we have finally implemented the basic functions of ToDoList as follows:
Add more styles if you like.
You can add more functions in the subsequent learning process to consolidate what you have learned.
The road ahead is long, and I see no end.
The attached ToDoList. Js code
import './ToDoList.css';
// Introduce React and useState
import React, { useState } from 'react'
// Add the charge form component
class ItemForm extends React.Component {
constructor(props) {
super(props)
this.state = { value: ' ' }
// This binding is necessary in order to use 'this' in callbacks
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)}// Input box content changes, update state
handleChange(event) {
this.setState({ value: event.target.value })
}
// Click the submit button, save the option, please enter the content blank
handleSubmit(event) {
event.preventDefault()
if(!this.state.value){
return
}
this.props.addNewItem(this.state.value)
this.setState({ value: ' '})}render() {
return (
<form onSubmit={this.handleSubmit}>
<label>To do:<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>)}}// To-do list component
function ItemList(props) {
// Click Finish to trigger the parent component method
function clickDelete(index) {
props.deleteItem(index)
}
// Use map to traverse the incoming array and return the rendered list
const ItemLists = props.items.map((item, index) = > (
// Elements in the map() method require a key attribute.
<li key={item.id}>
{item.title}
<button onClick={()= >ClickDelete (index)} ></button>
</li>
))
return ItemLists
}
function ToDoList() {
// Initialize the ID
const [itemId, setItemId] = useState(4)
// Initialize the to-do list array
const [items, setItems] = useState([
{
id: 1.title: 'eat'}, {id: 2.title: 'sleep'}, {id: 3.title: 'Beat the beans',}])// Complete the to-do list
function deleteItem(index) {
items.splice(index,1)
setItems([...items])
}
// Add todo
function addNewItem(data) {
let obj= {
id:itemId,
title:data
}
items.push(obj)
setItemId(itemId + 1)
setItems(items)
}
return (
<div className="App">
<h1>To Do List</h1>{/* Add list */}<ItemForm addNewItem={addNewItem}></ItemForm>
<ul>{/* Pass the to-do array to the component and bind the delete method */}<ItemList deleteItem={deleteItem} items={items}></ItemList>
</ul>
</div>
);
}
export default ToDoList;
Copy the code
Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address
dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.
Based on thegithub.com/danygitgitOn the creation of works.
Use rights other than those authorized by this License agreement may be obtained fromCreativecommons.org/licenses/by…Obtained.