精华内容
下载资源
问答
  • react示例React (also known as React.js) is one of the most popular JavaScript front end development libraries. Here is a collection of React syntax and usage that you can use as a handy guide or ...

    react示例

    React (also known as React.js) is one of the most popular JavaScript front end development libraries. Here is a collection of React syntax and usage that you can use as a handy guide or reference.

    React(也称为React.js)是最流行JavaScript前端开发库之一。 这是React语法和用法的集合,您可以将其用作方便的指南或参考。

    React组件示例 (React Component Example)

    Components are reusable in React.js. You can inject value into props as given below:

    组件可在React.js中重用。 您可以如下所示将值注入道具:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    const element = <Welcome name="Faisal Arkan" />;
    ReactDOM.render(
      element,
      document.getElementById('root')
    );

    name="Faisal Arkan" will give value into {props.name} from function Welcome(props) and returning a component that has given value by name="Faisal Arkan". After that React will render the element into html.

    name="Faisal Arkan"将通过function Welcome(props)将值{props.name}并返回一个具有name="Faisal Arkan"值的组件。 之后,React会将元素渲染为html。

    声明组件的其他方式 (Other ways to declare components)

    There are many ways to declare components when using React.js. There are two kinds of components, stateless components and stateful components.

    使用React.js时有很多方法来声明组件。 组件有两种, 无状态组件和有状态组件。

    有状态的 (Stateful)

    类类型组件 (Class Type Components)

    class Cat extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          humor: 'happy'
        }
      }
      render() {
        return(
          <div>
            <h1>{this.props.name}</h1>
            <p>
              {this.props.color}
            </p>
          </div>
        );
      }
    }

    无状态组件 (Stateless Components)

    功能组件(ES6中的箭头功能) (Functional Components (Arrow Function from ES6))

    const Cat = props => {
      return (  
        <div>
          <h1>{props.name}</h1>
          <p>{props.color}</p>
        </div>;
      );
    };

    隐式返回组件 (Implicit Return Components)

    const Cat = props => 
      <div>
        <h1>{props.name}</h1>
        <p>{props.color}</p>
      </div>;

    React片段示例 (React Fragment Example)

    Fragments are way to render multiple elements without using a wrapper element. When attempting to render elements without an enclosing tag in JSX, you will see the error message Adjacent JSX elements must be wrapped in an enclosing tag. This is because when JSX transpiles, it’s creating elements with their corresponding tag names, and doesn’t know what tag name to use if multiple elements are found.

    片段是一种无需使用包装元素即可呈现多个元素的方法。 尝试在JSX中呈现不带有封闭标记的元素时,您将看到错误消息, Adjacent JSX elements must be wrapped in an enclosing tag 。 这是因为当JSX转换时,它正在创建具有其相应标签名称的元素,并且如果找到多个元素,则不知道要使用哪个标签名称。

    In the past, a frequent solution to this was to use a wrapper div to solve this problem. However, version 16 of React brought the addition of Fragment, which makes this no longer necessary.

    过去,对此的常见解决方案是使用wrapper div解决此问题。 但是,React的版本16带来了Fragment的添加,这使得它不再必要。

    Fragment acts a wrapper without adding unnecessary divs to the DOM. You can use it directly from the React import, or deconstruct it:

    Fragment充当包装器,而没有向DOM添加不必要的div。 您可以直接从React导入中使用它,也可以对其进行解构:

    import React from 'react';
    
    class MyComponent extends React.Component {
      render(){
        return (
          <React.Fragment>
            <div>I am an element!</div>
            <button>I am another element</button>
          </React.Fragment>
        );
      }
    }
    
    export default MyComponent;
    // Deconstructed
    import React, { Component, Fragment } from 'react';
    
    class MyComponent extends Component {
      render(){
        return (
          <Fragment>
            <div>I am an element!</div>
            <button>I am another element</button>
          </Fragment>
        );
      }
    }
    
    export default MyComponent;

    React version 16.2 simplified this process further, allowing for empty JSX tags to be interpreted as Fragments:

    React版本16.2进一步简化了此过程,允许将空的JSX标签解释为片段:

    return (
      <>
        <div>I am an element!</div>
        <button>I am another element</button>
      </>
    );

    React JSX示例 (React JSX Example)

    JSX (JSX)

    JSX is short for JavaScript XML.

    JSX是JavaScript XML的缩写。

    JSX is an expression which uses valid HTML statements within JavaScript. You can assign this expression to a variable and use it elsewhere. You can combine other valid JavaScript expressions and JSX within these HTML statements by placing them within braces ({}). Babel further compiles JSX into an object of type React.createElement().

    JSX是在JavaScript中使用有效HTML语句的表达式。 您可以将此表达式分配给变量,并在其他地方使用它。 您可以将其他有效JavaScript表达式和JSX放在这些HTML语句中,方法是将它们放在花括号( {} )中。 Babel进一步将JSX编译为React.createElement()类型的对象。

    单行和多行表达式 (Single-line & Multi-line expressions)

    Single-line expression are simple to use.

    单行表达式易于使用。

    const one = <h1>Hello World!</h1>;

    When you need to use multiple lines in a single JSX expression, write the code within a single parenthesis.

    当您需要在单个JSX表达式中使用多行时,请在单个括号内编写代码。

    const two = (
      <ul>
        <li>Once</li>
        <li>Twice</li>
      </ul>
    );

    仅使用HTML标签 (Using only HTML tags)

    const greet = <h1>Hello World!</h1>;

    将JavaScript表达式与HTML标签结合 (Combining JavaScript expression with HTML tags)

    We can use JavaScript variables within braces.

    我们可以在括号内使用JavaScript变量。

    const who = "Quincy Larson";
    const greet = <h1>Hello {who}!</h1>;

    We can also call other JavaScript functions within braces.

    我们还可以在花括号内调用其他JavaScript函数。

    function who() {
      return "World";
    }
    const greet = <h1>Hello {who()}!</h1>;

    只允许使用一个父标签 (Only a single parent tag is allowed)

    A JSX expression must have only one parent tag. We can add multiple tags nested within the parent element only.

    JSX表达式必须只有一个父标记。 我们只能添加嵌套在父元素内的多个标签。

    // This is valid.
    const tags = (
      <ul>
        <li>Once</li>
        <li>Twice</li>
      </ul>
    );
    
    // This is not valid.
    const tags = (
      <h1>Hello World!</h1>
      <h3>This is my special list:</h3>
      <ul>
        <li>Once</li>
        <li>Twice</li>
      </ul>
    );

    React状态示例 (React State Example)

    State is the place where the data comes from.

    状态是数据来源的地方。

    We should always try to make our state as simple as possible and minimize the number of stateful components. If we have, for example, ten components that need data from the state, we should create one container component that will keep the state for all of them.

    我们应该始终尝试使状态尽可能简单,并尽量减少有状态组件的数量。 例如,如果我们有十个需要状态数据的组件,则应该创建一个容器组件,以保持所有状态的状态。

    State is basically like a global object that is available everywhere in a component.

    状态基本上就像一个全局对象,可以在组件中的任何地方使用。

    Example of a Stateful Class Component:

    有状态类组件的示例:

    import React from 'react';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
          
        // We declare the state as shown below
        
        this.state = {                           
          x: "This is x from state",    
          y: "This is y from state"
        }
      }
      render() {
        return (
          <div>
            <h1>{this.state.x}</h1>
            <h2>{this.state.y}</h2>
          </div>
        );
      }
    }
    export default App;

    Another Example:

    另一个例子:

    import React from 'react';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        
        // We declare the state as shown below
        this.state = {                           
          x: "This is x from state",    
          y: "This is y from state"
        }
      }
    
      render() {
        let x1 = this.state.x;
        let y1 = this.state.y;
    
        return (
          <div>
            <h1>{x1}</h1>
            <h2>{y1}</h2>
          </div>
        );
      }
    }
    export default App;

    更新状态 (Updating State)

    You can change the data stored in the state of your application using the setState method on your component.

    您可以使用组件上的setState方法更改存储在应用程序状态中的数据。

    this.setState({ value: 1 });

    Keep in mind that setState is asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.

    请记住, setState是异步的,因此在使用当前状态设置新状态时应格外小心。 一个很好的例子是,如果您想在状态中增加一个值。

    错误的方法 (The Wrong Way)

    this.setState({ value: this.state.value + 1 });

    This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to setState instead of an object.

    如果在同一更新周期内多次调用上述代码,则可能会导致应用程序出现意外行为。 为了避免这种情况,您可以将更新程序回调函数传递给setState而不是对象。

    正确的方式 (The Right Way)

    this.setState(prevState => ({ value: prevState.value + 1 }));

    更新状态 (Updating State)

    You can change the data stored in the state of your application using the setState method on your component.

    您可以使用组件上的setState方法更改存储在应用程序状态中的数据。

    this.setState({value: 1});

    Keep in mind that setState may be asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.

    请记住, setState可能是异步的,因此在使用当前状态设置新状态时应小心。 一个很好的例子是,如果您想在状态中增加一个值。

    错误的方法 (The Wrong Way)
    this.setState({value: this.state.value + 1});

    This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to setState instead of an object.

    如果在同一更新周期内多次调用上述代码,则可能会导致应用程序出现意外行为。 为了避免这种情况,您可以将更新程序回调函数传递给setState而不是对象。

    正确的方式 (The Right Way)
    this.setState(prevState => ({value: prevState.value + 1}));
    清洁方式 (The Cleaner Way)
    this.setState(({ value }) => ({ value: value + 1 }));

    When only a limited number of fields in the state object is required, object destructing can be used for cleaner code.

    当状态对象中只需要有限数量的字段时,对象销毁可用于更干净的代码。

    React状态VS道具示例 (React State VS Props Example)

    When we start working with React components, we frequently hear two terms. They are state and props. So, in this article we will explore what are those and how they differ.

    当我们开始使用React组件时,我们经常听到两个术语。 他们是stateprops 。 因此,在本文中,我们将探讨这些内容以及它们之间的区别。

    州: (State:)

    • State is something that a component owns. It belongs to that particular component where it is defined. For example, a person’s age is a state of that person.

      状态是组件拥有的东西。 它属于定义它的那个特定组件。 例如,一个人的年龄就是那个人的状态。
    • State is mutable. But it can be changed only by that component that owns it. As I only can change my age, not anyone else.

      状态是易变的。 但是只能由拥有它的那个组件来更改。 因为我只能改变年龄,没有其他人可以改变。
    • You can change a state by using this.setState()

      您可以使用this.setState()更改状态

    See the below example to get an idea of state:

    请参阅以下示例以了解状态:

    Person.js (Person.js)

    import React from 'react';
    
      class Person extends React.Component{
        constructor(props) {
          super(props);
          this.state = {
            age:0
          this.incrementAge = this.incrementAge.bind(this)
        }
    
        incrementAge(){
          this.setState({
            age:this.state.age + 1;
          });
        }
    
        render(){
          return(
            <div>
              <label>My age is: {this.state.age}</label>
              <button onClick={this.incrementAge}>Grow me older !!<button>
            </div>
          );
        }
      }
    
      export default Person;

    In the above example, age is the state of Person component.

    在上面的示例中, age是“ Person组件的状态。

    道具: (Props:)

    • Props are similar to method arguments. They are passed to a component where that component is used.

      道具类似于方法参数。 它们被传递到使用该组件的组件。
    • Props is immutable. They are read-only.

      道具是一成不变的。 它们是只读的。

    See the below example to get an idea of Props:

    请参阅以下示例以了解道具:

    Person.js (Person.js)

    import React from 'react';
    
      class Person extends React.Component{
        render(){
          return(
            <div>
              <label>I am a {this.props.character} person.</label>
            </div>
          );
        }
      }
    
      export default Person;
    
      const person = <Person character = "good"></Person>

    In the above example, const person = <Person character = "good"></Person> we are passing character = "good" prop to Person component.

    在上面的示例中, const person = <Person character = "good"></Person>我们将character = "good"传递给Person组件。

    It gives output as “I am a good person”, in fact I am.

    它给出的输出是“我是一个好人”,事实上我是。

    There is lot more to learn on State and Props. Many things can be learnt by actually diving into coding. So get your hands dirty by coding.

    关于状态和道具还有很多要学习的东西。 通过实际研究编码,可以学到很多东西。 因此,通过编码使您的手变脏。

    React高阶组件示例 (React Higher-Order Component Example)

    In React, a Higher-Order Component (HOC) is a function that takes a component and returns a new component. Programmers use HOCs to achieve component logic reuse.

    在React中, 高阶组件 (HOC)是一个接受组件并返回新组件的函数。 程序员使用HOC来实现组件逻辑的重用

    If you’ve used Redux’s connect, you’ve already worked with Higher-Order Components.

    如果您使用过Redux的connect ,那么您已经使用了高阶组件。

    The core idea is:

    核心思想是:

    const EnhancedComponent = enhance(WrappedComponent);

    Where:

    哪里:

    • enhance is the Higher-Order Component;

      enhance是高阶组件;

    • WrappedComponent is the component you want to enhance; and

      WrappedComponent是您要增强的组件; 和

    • EnhancedComponent is the new component created.

      EnhancedComponent是创建的新组件。

    This could be the body of the enhance HOC:

    这可能是enhance HOC的主体:

    function enhance(WrappedComponent) {
      return class extends React.Component {
        render() {
          const extraProp = 'This is an injected prop!';
          return (
            <div className="Wrapper">
              <WrappedComponent
                {...this.props}
                extraProp={extraProp}
              />
            </div>
          );
        }
      }
    }

    In this case, enhance returns an anonymous class that extends React.Component. This new component is doing three simple things:

    在这种情况下, enhance回报率,扩展一个匿名类 React.Component 。 这个新组件正在做三件简单的事情:

    • Rendering the WrappedComponent within a div element;

      div元素中渲染WrappedComponent

    • Passing its own props to the WrappedComponent; and

      将自己的道具传递给WrappedComponent ; 和

    • Injecting an extra prop to the WrappedComponent.

      WrappedComponent注入额外的道具。

    HOCs are just a pattern that uses the power of React’s compositional nature. They add features to a component. There are a lot more things you can do with them!

    HOC只是一种使用React的组合性质的模式。 它们向组件添加功能 。 您可以使用它们做更多的事情!

    翻译自: https://www.freecodecamp.org/news/react-examples-reactjs/

    react示例

    展开全文
  • 将markdown转换成实时React示例
  • react-react示例项目

    2019-08-14 20:22:35
    这是react示例项目, 主要用于参考npm和webpack的配置方法.
  • 增加 Vue / React 示例

    2020-12-08 20:54:18
    <div><p>您好! 不知道有没有增加 Vue / React 示例的计划呢?</p><p>该提问来源于开源项目:Qquanwei/trackpoint-tools</p></div>
  • react 示例 我们在建什么? (What are we building?) Today. We will build a react app with a button and a paragraph in a div element. The React JS app will allow us to click on the button and increment ...

    react 示例

    我们在建什么? (What are we building?)

    Today. We will build a react app with a button and a paragraph in a div element. The React JS app will allow us to click on the button and increment or increase a figure as many times as it is being clicked.

    今天。 我们将在div元素中构建一个带有按钮和段落的react应用。 React JS应用程序将允许我们单击按钮,并增加或增加被单击的次数。

    You should have some basic knowledge of React JS and web development to understand this project.

    您应该具有React JS和Web开发的一些基本知识,以理解该项目。

    Move on to your "src" folder found in your create react app template and let's edit and modify 2 files.

    移至在create react应用程序模板中找到的“ src”文件夹 ,让我们编辑和修改2个文件。

    Open your index.js file and type the following as usual,

    打开index.js文件,然后像往常一样键入以下内容,

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
    
    ReactDOM.render(<App />, document.getElementById('root'))
    
    

    The code above is the normal convention and syntax we always start a react app, which is importing necessary dependencies and components for our React JS app.

    上面的代码是我们始终启动react应用程序的常规约定和语法,这将为React JS应用程序导入必要的依赖项和组件。

    React and react-dom are like the necessary libraries required to run a react app on a local development server (depending on installation method) while App is the React JS component (which is equally an external file with the name App) where we will do the real coding.

    React和react-dom就像在本地开发服务器上运行React App所需的必要库(取决于安装方法),而App是React JS组件(同样是名为App的外部文件),我们将在其中进行操作真正的编码。

    Open App.js file and type the following,

    打开App.js文件并输入以下内容,

    In this file, we will import react, create a class component and export the component.

    在这个文件中,我们将导入react,创建一个类组件并导出该组件。

    import React from "react"
    
    class App extends React.Component {
    	constructor (props) {
    		super (props)
    		// create a state with a property count set to 0
    		this.state = {
    		count : 0
    		}
    		// bind the method to the class component 
    		this.go = this.go.bind(this)
    	}
    
    	// event handler function 
    	go () {
    		// set the new state by getting previous state 
    		// using (prevState) and increase by 1 
    		this.setState (  prevState => {
    			return {
    				count : prevState.count + 1
    			}
    		})
    	} 
    
    	render() {
    		return (
    			<div> 
    				<center>
    				<p> {this.state.count}  <button onClick= {this.go} > like! </button> </p>
    				</center>
    			</div>
    		)
    	}
    }
    export default App
    
    

    Explanation:

    说明:

    From the code above, we created a class called App and added a constructor method with our state object.

    从上面的代码,我们创建了一个名为App的类,并在状态对象中添加了一个构造方法。

    The state object has a property count which is set to 0.

    状态对象的属性计数设置为0

    The next line contains a keyword called bind which is very important in our React JS app.

    下一行包含一个名为bind的关键字,这在我们的React JS应用程序中非常重要。

    It is a concept never to forget:

    这是一个永远不会忘记的概念:

    Whenever you create a class method (go ()) that you want to use setState() on, you have to bind the method to your class (class App).

    每当创建要使用setState()的类方法( go() )时,都必须将该方法绑定到您的类(App类)

    Next, we created our event handler (go()) sets the state to a new value by first of all checking the previous state and then increases it by 1.

    接下来,我们创建了事件处理程序( go() ),首先检查先前的状态,然后将其增加1,从而将状态设置为新值。

    Output:

    输出:

    Create a sample Facebook like button using React JS | Output 1




    Create a sample Facebook like button using React JS | Output 2

    Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.

    感谢您与我编码! 下次见。 随意发表评论或问题。

    翻译自: https://www.includehelp.com/react-js/how-to-create-a-sample-facebook-like-button-using-react-js.aspx

    react 示例

    展开全文
  • react 示例I've put together for you an entire visual cheatsheet of all of the concepts and skills you need to master React in 2020. 我为您汇总了2020年掌握React所需的所有概念和技能的完整视觉摘要。 But...

    react 示例

    I've put together for you an entire visual cheatsheet of all of the concepts and skills you need to master React in 2020.

    我为您汇总了2020年掌握React所需的所有概念和技能的完整视觉摘要。

    But don't let the label 'cheatsheet' fool you. This is more than a mere summary of React's features.

    但不要让标签“备忘单”蒙骗您。 这不仅仅是React功能的总结。

    My aim here was to clearly and concisely put forth the knowledge and patterns I've gained through working with React as a professional developer.

    我的目的是清楚,简洁地提出通过与React作为专业开发人员合作而获得的知识和模式。

    Each part is designed to be immensely helpful by showing you real-world, practical examples with meaningful comments to guide you along the way.

    通过向您展示真实实用的示例以及有意义的注释来指导您的工作,每个部分都将为您提供极大的帮助。

    想要自己的副本? 📄 (Want Your Own Copy? 📄)

    Grab the PDF cheatsheet right here (it takes 5 seconds).

    此处获取PDF速查表(需要5秒钟)。

    Here are some quick wins from grabbing the downloadable version:

    从下载可下载版本中可以快速获得一些好处:

    • ✓ Quick reference guide to review however and whenever

      ✓快速参考指南,可随时随地进行审核
    • ✓ Tons of copyable code snippets for easy reuse

      ✓大量可复制的代码片段,易于重用
    • ✓ Read this massive guide wherever suits you best. On the train, at your desk, standing in line... anywhere.

      ✓阅读最适合您的详细指南。 在火车上,在您的办公桌前,在任何地方排队。
    Note: There is limited coverage of class components in this cheatsheet. Class components are still valuable to know for existing React projects, but since the arrival of Hooks in 2018, we are able to make our apps with function components alone. I wanted to give beginners and experienced developers alike a Hooks-first approach treatment of React.
    注意:本备忘单中类组件的覆盖范围有限。 对于现有的React项目,类组件仍然是有价值的知识,但是自从Hooks在2018年问世以来,我们就能够使我们的应用程序仅包含功能组件。 我想给初学者和经验丰富的开发人员一样对Hooks的Hooks优先方法的对待。

    There's a ton of great stuff to cover, so let's get started.

    有很多很棒的东西要介绍,所以让我们开始吧。

    目录 (Table of Contents)

    核心概念 (Core Concepts)

    • Elements and JS

      元素和JS
    • Components and Props

      组件和道具
    • Lists and Keys

      列表和键
    • Events and Event Handlers

      事件和事件处理程序

    React钩 (React Hooks)

    • State and useState

      状态和使用状态
    • Side Effects and useEffect

      副作用和使用效果
    • Performance and useCallback

      性能和使用回调
    • Memoization and useMemo

      备注和使用备注
    • Refs and useRef

      参考和使用参考

    高级挂钩 (Advanced Hooks)

    • Context and useContext

      上下文和useContext
    • Reducers and useReducer

      减速器及使用
    • Writing custom hooks

      编写自定义钩子
    • Rules of hooks

      钩子规则

    核心概念 (Core Concepts)

    Elements和JSX (Elements and JSX)

    This is the basic syntax for a React element:

    这是React元素的基本语法:

    // In a nutshell, JSX allows us to write HTML in our JS
    // JSX can use any valid html tags (i.e. div/span, h1-h6, form/input, etc)
    <div>Hello React</div>

    JSX elements are expressions:

    JSX元素是表达式:

    // as an expression, JSX can be assigned to variables...
    const greeting = <div>Hello React</div>;
    
    const isNewToReact = true;
    
    // ... or can be displayed conditionally
    function sayGreeting() {
      if (isNewToReact) {
        // ... or returned from functions, etc.
        return greeting; // displays: Hello React
      } else {
        return <div>Hi again, React</div>;
      }
    }

    JSX allows us to nest expressions:

    JSX允许我们嵌套表达式:

    const year = 2020;
    // we can insert primitive JS values in curly braces: {}
    const greeting = <div>Hello React in {year}</div>;
    // trying to insert objects will result in an error

    JSX allows us to nest elements:

    JSX允许我们嵌套元素:

    // to write JSX on multiple lines, wrap in parentheses: ()
    const greeting = (
      // div is the parent element
      <div>
        {/* h1 and p are child elements */}
        <h1>Hello!</h1>
        <p>Welcome to React</p>
      </div>
    );
    // 'parents' and 'children' are how we describe JSX elements in relation
    // to one another, like we would talk about HTML elements

    HTML and JSX have a slightly different syntax:

    HTML和JSX的语法略有不同:

    // Empty div is not <div></div> (HTML), but <div/> (JSX)
    <div/>
    
    // A single tag element like input is not <input> (HTML), but <input/> (JSX)
    <input name="email" />
    
    // Attributes are written in camelcase for JSX (like JS variables
    <button className="submit-button">Submit</button> // not 'class' (HTML)

    The most basic React app requires three things:

    最基本的React应用程序需要三件事:

    • ReactDOM.render() to render our app

      ReactDOM.render()渲染我们的应用
    • A JSX element (called a root node in this context)

      JSX元素(在此上下文中称为根节点)
    • A DOM element within which to mount the app (usually a div with an id of root in an index.html file)

      一个要在其中安装应用程序的DOM元素(通常是index.html文件中ID为root的div)
    // imports needed if using NPM package; not if from CDN links
    import React from "react";
    import ReactDOM from "react-dom";
    
    const greeting = <h1>Hello React</h1>;
    
    // ReactDOM.render(root node, mounting point)
    ReactDOM.render(greeting, document.getElementById("root"));

    组件和道具 (Components and Props)

    This is the syntax for a basic React component:

    这是基本的React组件的语法:

    import React from "react";
    
    // 1st component type: function component
    function Header() {
      // function components must be capitalized unlike normal JS functions
      // note the capitalized name here: 'Header'
      return <h1>Hello React</h1>;
    }
    
    // function components with arrow functions are also valid
    const Header = () => <h1>Hello React</h1>;
    
    // 2nd component type: class component
    // (classes are another type of function)
    class Header extends React.Component {
      // class components have more boilerplate (with extends and render method)
      render() {
        return <h1>Hello React</h1>;
      }
    }

    This is how components are used:

    这是组件的使用方式:

    // do we call these function components like normal functions?
    
    // No, to execute them and display the JSX they return...
    const Header = () => <h1>Hello React</h1>;
    
    // ...we use them as 'custom' JSX elements
    ReactDOM.render(<Header />, document.getElementById("root"));
    // renders: <h1>Hello React</h1>

    Components can be reused across our app:

    组件可以在我们的应用程序中重复使用:

    // for example, this Header component can be reused in any app page
    
    // this component shown for the '/' route
    function IndexPage() {
      return (
        <div>
          <Header />
          <Hero />
          <Footer />
        </div>
      );
    }
    
    // shown for the '/about' route
    function AboutPage() {
      return (
        <div>
          <Header />
          <About />
          <Testimonials />
          <Footer />
        </div>
      );
    }

    Data can be dynamically passed to components with props:

    数据可以通过props动态传递给组件:

    // What if we want to pass data to our component from a parent?
    // I.e. to pass a user's name to display in our Header?
    
    const username = "John";
    
    // we add custom 'attributes' called props
    ReactDOM.render(
      <Header username={username} />,
      document.getElementById("root")
    );
    // we called this prop 'username', but can use any valid JS identifier
    
    // props is the object that every component receives as an argument
    function Header(props) {
      // the props we make on the component (i.e. username)
      // become properties on the props object
      return <h1>Hello {props.username}</h1>;
    }

    Props must never be directly changed (mutated):

    道具绝不能直接更改(变异):

    // Components must ideally be 'pure' functions.
    // That is, for every input, we be able to expect the same output
    
    // we cannot do the following with props:
    function Header(props) {
      // we cannot mutate the props object, we can only read from it
      props.username = "Doug";
    
      return <h1>Hello {props.username}</h1>;
    }
    // But what if we want to modify a prop value that comes in?
    // That's where we would use state (see the useState section)

    Children props are useful if we want to pass elements / components as props to other components.

    如果我们想将元素/组件作为道具传递给其他组件,则子道具很有用。

    // Can we accept React elements (or components) as props?
    // Yes, through a special property on the props object called 'children'
    
    function Layout(props) {
      return <div className="container">{props.children}</div>;
    }
    
    // The children prop is very useful for when you want the same
    // component (such as a Layout component) to wrap all other components:
    function IndexPage() {
      return (
        <Layout>
          <Header />
          <Hero />
          <Footer />
        </Layout>
      );
    }
    
    // different page, but uses same Layout component (thanks to children prop)
    function AboutPage() {
      return (
        <Layout>
          <About />
          <Footer />
        </Layout>
      );
    }

    Conditionally displaying components with ternaries and short-circuiting:

    有条件地显示具有三元和短路的组件:

    // if-statements are fine to conditionally show , however...
    // ...only ternaries (seen below) allow us to insert these conditionals
    // in JSX, however
    function Header() {
      const isAuthenticated = checkAuth();
    
      return (
        <nav>
          <Logo />
          {/* if isAuth is true, show AuthLinks. If false, Login  */}
          {isAuthenticated ? <AuthLinks /> : <Login />}
          {/* if isAuth is true, show Greeting. If false, nothing. */}
          {isAuthenticated && <Greeting />}
        </nav>
      );
    }

    Fragments are special components for displaying multiple components without adding an extra element to the DOM.

    片段是特殊的组件,用于显示多个组件,而无需向DOM添加额外的元素。

    Fragments are ideal for conditional logic:

    片段是条件逻辑的理想选择:

    // we can improve the logic in the previous example
    // if isAuthenticated is true, how do we display both AuthLinks and Greeting?
    function Header() {
      const isAuthenticated = checkAuth();
    
      return (
        <nav>
          <Logo />
          {/* we can render both components with a fragment */}
          {/* fragments are very concise: <> </> */}
          {isAuthenticated ? (
            <>
              <AuthLinks />
              <Greeting />
            </>
          ) : (
            <Login />
          )}
        </nav>
      );
    }

    列表和键 (Lists and Keys)

    Use .map() to convert lists of data (arrays) into lists of elements:

    使用.map()将数据(数组)列表转换为元素列表:

    const people = ["John", "Bob", "Fred"];
    const peopleList = people.map(person => <p>{person}</p>);

    .map() is also used for components as well as elements:

    .map()也用于组件和元素:

    function App() {
      const people = ['John', 'Bob', 'Fred'];
      // can interpolate returned list of elements in {}
      return (
        <ul>
          {/* we're passing each array element as props */}
          {people.map(person => <Person name={person} />}
        </ul>
      );
    }
    
    function Person({ name }) {
      // gets 'name' prop using object destructuring
      return <p>this person's name is: {name}</p>;
    }

    Each React element iterated over needs a special 'key' prop. Keys are essential for React to be able to keep track of each element that is being iterated over with map

    每个迭代的React元素都需要一个特殊的“关键”道具。 密钥对于React至关重要,以便能够跟踪正在被map迭代的每个元素

    Without keys, it is harder for it to figure out how elements should be updated when data changes.

    如果没有键,则很难确定在数据更改时应如何更新元素。

    Keys should be unique values to represent the fact that these elements are separate from one another.

    键应该是唯一的值,以表示这些元素彼此分开的事实。

    function App() {
      const people = ['John', 'Bob', 'Fred'];
    
      return (
        <ul>
          {/* keys need to be primitive values, ideally a generated id */}
          {people.map(person => <Person key={person} name={person} />)}
        </ul>
      );
    }
    
    // If you don't have ids with your set of data or unique primitive values,
    // you can use the second parameter of .map() to get each elements index
    function App() {
      const people = ['John', 'Bob', 'Fred'];
    
      return (
        <ul>
          {/* use array element index for key */}
          {people.map((person, i) => <Person key={i} name={person} />)}
        </ul>
      );
    }

    事件和事件处理程序 (Events and Event Handlers)

    Events in React and HTML are slightly different.

    React和HTML中的事件略有不同。

    // Note: most event handler functions start with 'handle'
    function handleToggleTheme() {
      // code to toggle app theme
    }
    
    // in html, onclick is all lowercase
    <button onclick="handleToggleTheme()">
      Submit
    </button>
    
    // in JSX, onClick is camelcase, like attributes / props
    // we also pass a reference to the function with curly braces
    <button onClick={handleToggleTheme}>
      Submit
    </button>

    The most essential React events to know are onClick and onChange.

    要了解的最重要的React事件是onClick和onChange。

    • onClick handles click events on JSX elements (namely buttons)

      onClick处理JSX元素(即按钮)上的点击事件
    • onChange handles keyboard events (namely inputs)

      onChange处理键盘事件(即输入)
    function App() {
      function handleChange(event) {
        // when passing the function to an event handler, like onChange
        // we get access to data about the event (an object)
        const inputText = event.target.value;
        const inputName = event.target.name; // myInput
        // we get the text typed in and other data from event.target
      }
    
      function handleSubmit() {
        // on click doesn't usually need event data
      }
    
      return (
        <div>
          <input type="text" name="myInput" onChange={handleChange} />
          <button onClick={handleSubmit}>Submit</button>
        </div>
      );
    }

    React钩 (React Hooks)

    状态和使用状态 (State and useState)

    useState gives us local state in a function component:

    useState在函数组件中为我们提供本地状态:

    import React from 'react';
    
    // create state variable
    // syntax: const [stateVariable] = React.useState(defaultValue);
    function App() {
      const [language] = React.useState('javascript');
      // we use array destructuring to declare state variable
    
      return <div>I am learning {language}</div>;
    }

    Note: Any hook in this section is from the React package and can be imported individually.

    注意:本节中的任何钩子都来自React包,可以单独导入。

    import React, { useState } from "react";
    
    function App() {
      const [language] = useState("javascript");
    
      return <div>I am learning {language}</div>;
    }

    useState also gives us a 'setter' function to update the state it creates:

    useState还为我们提供了一个“设置器”功能来更新其创建的状态:

    function App() {
      // the setter function is always the second destructured value
      const [language, setLanguage] = React.useState("python");
      // the convention for the setter name is 'setStateVariable'
    
      return (
        <div>
          {/*  why use an arrow function here instead onClick={setterFn()} ? */}
          <button onClick={() => setLanguage("javascript")}>
            Change language to JS
          </button>
          {/*  if not, setLanguage would be called immediately and not on click */}
          <p>I am now learning {language}</p>
        </div>
      );
    }
    
    // note that whenever the setter function is called, the state updates,
    // and the App component re-renders to display the new state

    useState can be used once or multiple times within a single component:

    useState可以在单个组件中使用一次或多次:

    function App() {
      const [language, setLanguage] = React.useState("python");
      const [yearsExperience, setYearsExperience] = React.useState(0);
    
      return (
        <div>
          <button onClick={() => setLanguage("javascript")}>
            Change language to JS
          </button>
          <input
            type="number"
            value={yearsExperience}
            onChange={event => setYearsExperience(event.target.value)}
          />
          <p>I am now learning {language}</p>
          <p>I have {yearsExperience} years of experience</p>
        </div>
      );
    }

    useState can accept primitive or object values to manage state:

    useState可以接受原始值或对象值来管理状态:

    // we have the option to organize state using whatever is the
    // most appropriate data type, according to the data we're tracking
    function App() {
      const [developer, setDeveloper] = React.useState({
        language: "",
        yearsExperience: 0
      });
    
      function handleChangeYearsExperience(event) {
        const years = event.target.value;
        // we must pass in the previous state object we had with the spread operator
        setDeveloper({ ...developer, yearsExperience: years });
      }
    
      return (
        <div>
          {/* no need to get prev state here; we are replacing the entire object */}
          <button
            onClick={() =>
              setDeveloper({
                language: "javascript",
                yearsExperience: 0
              })
            }
          >
            Change language to JS
          </button>
          {/* we can also pass a reference to the function */}
          <input
            type="number"
            value={developer.yearsExperience}
            onChange={handleChangeYearsExperience}
          />
          <p>I am now learning {developer.language}</p>
          <p>I have {developer.yearsExperience} years of experience</p>
        </div>
      );
    }

    If the new state depends on the previous state, to guarantee that the update is done reliably, we can use a function within the setter function that gives us the correct previous state.

    如果新状态依赖于先前状态,则为保证可靠地完成更新,我们可以在setter函数中使用一个函数,该函数为我们提供正确的先前状态。

    function App() {
      const [developer, setDeveloper] = React.useState({
        language: "",
        yearsExperience: 0,
        isEmployed: false
      });
    
      function handleToggleEmployment(event) {
        // we get the previous state variable's value in the parameters
        // we can name 'prevState' however we like
        setDeveloper(prevState => {
          return { ...prevState, isEmployed: !prevState.isEmployed };
          // it is essential to return the new state from this function
        });
      }
    
      return (
        <button onClick={handleToggleEmployment}>Toggle Employment Status</button>
      );
    }

    副作用和使用效果 (Side effects and useEffect)

    useEffect lets us perform side effects in function components. So what are side effects?

    useEffect让我们在功能组件中执行副作用。 那么什么是副作用呢?

    • Side effects are where we need to reach into the outside world. For example, fetching data from an API or working with the DOM.

      副作用是我们需要接触外界的地方。 例如,从API提取数据或使用DOM。
    • Side effects are actions that can change our component state in an unpredictable fashion (that have caused 'side effects').

      副作用是可以以不可预测的方式更改组件状态的动作(已引起“副作用”)。

    useEffect accepts a callback function (called the 'effect' function), which will by default run every time there is a re-render. It runs once our component mounts, which is the right time to perform a side effect in the component lifecycle.

    useEffect接受一个回调函数(称为“效果”函数),默认情况下,它将在每次重新渲染时运行。 一旦我们的组件安装好,它就会运行,这是在组件生命周期中产生副作用的正确时机。

    // what does our code do? Picks a color from the colors array
    // and makes it the background color
    function App() {
      const [colorIndex, setColorIndex] = React.useState(0);
      const colors = ["blue", "green", "red", "orange"];
    
      // we are performing a 'side effect' since we are working with an API
      // we are working with the DOM, a browser API outside of React
      useEffect(() => {
        document.body.style.backgroundColor = colors[colorIndex];
      });
      // whenever state is updated, App re-renders and useEffect runs
    
      function handleChangeIndex() {
        const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1;
        setColorIndex(next);
      }
    
      return <button onClick={handleChangeIndex}>Change background color</button>;
    }

    To avoid executing the effect callback after each render, we provide a second argument, an empty array:

    为了避免在每次渲染后执行效果回调,我们提供了第二个参数,一个空数组:

    function App() {
      ...
      // now our button doesn't work no matter how many times we click it...
      useEffect(() => {
        document.body.style.backgroundColor = colors[colorIndex];
      }, []);
      // the background color is only set once, upon mount
    
      // how do we not have the effect function run for every state update...
      // but still have it work whenever the button is clicked?
    
      return (
        <button onClick={handleChangeIndex}>
          Change background color
        </button>
      );
    }

    useEffect lets us conditionally perform effects with the dependencies array.

    useEffect让我们有条件地执行依赖关系数组的效果。

    The dependencies array is the second argument, and if any one of the values in the array changes, the effect function runs again.

    依赖项数组是第二个参数,如果数组中的任何值发生更改,效果函数都会再次运行。

    function App() {
      const [colorIndex, setColorIndex] = React.useState(0);
      const colors = ["blue", "green", "red", "orange"];
    
      // we add colorIndex to our dependencies array
      // when colorIndex changes, useEffect will execute the effect fn again
      useEffect(() => {
        document.body.style.backgroundColor = colors[colorIndex];
        // when we use useEffect, we must think about what state values
        // we want our side effect to sync with
      }, [colorIndex]);
    
      function handleChangeIndex() {
        const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1;
        setColorIndex(next);
      }
    
      return <button onClick={handleChangeIndex}>Change background color</button>;
    }

    useEffect lets us unsubscribe from certain effects by returning a function at the end:

    useEffect让我们通过在最后返回一个函数来取消订阅某些效果:

    function MouseTracker() {
      const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
    
      React.useEffect(() => {
        // .addEventListener() sets up an active listener...
        window.addEventListener("mousemove", event => {
          const { pageX, pageY } = event;
          setMousePosition({ x: pageX, y: pageY });
        });
    
        // ...so when we navigate away from this page, it needs to be
        // removed to stop listening. Otherwise, it will try to set
        // state in a component that doesn't exist (causing an error)
    
        // We unsubscribe any subscriptions / listeners w/ this 'cleanup function'
        return () => {
          window.removeEventListener("mousemove", event => {
            const { pageX, pageY } = event;
            setMousePosition({ x: pageX, y: pageY });
          });
        };
      }, []);
    
      return (
        <div>
          <h1>The current mouse position is:</h1>
          <p>
            X: {mousePosition.x}, Y: {mousePosition.y}
          </p>
        </div>
      );
    }
    
    // Note: we could extract the reused logic in the callbacks to
    // their own function, but I believe this is more readable
    • Fetching data with useEffect

      使用useEffect获取数据

    Note that handling promises with the more concise async/await syntax requires creating a separate function. (Why? The effect callback function cannot be async.)

    请注意,使用更简洁的async / await语法处理Promise需要创建一个单独的函数。 (为什么?效果回调函数不能异步。)

    const endpoint = "https://api.github.com/users/codeartistryio";
    
    // with promises:
    function App() {
      const [user, setUser] = React.useState(null);
    
      React.useEffect(() => {
        // promises work in callback
        fetch(endpoint)
          .then(response => response.json())
          .then(data => setUser(data));
      }, []);
    }
    
    // with async / await syntax for promise:
    function App() {
      const [user, setUser] = React.useState(null);
      // cannot make useEffect callback function async
      React.useEffect(() => {
        getUser();
      }, []);
    
      // instead, use async / await in separate function, then call
      // function back in useEffect
      async function getUser() {
        const response = await fetch("https://api.github.com/codeartistryio");
        const data = await response.json();
        setUser(data);
      }
    }

    性能和使用回调 (Performance and useCallback)

    useCallback is a hook that is used for improving our component's performance.

    useCallback是一个挂钩,用于提高组件的性能。

    If you have a component that re-renders frequently, useCallback prevents callback functions within the component from being recreated every single time the component re-renders (which means the function component re-runs).

    如果您有一个频繁重新渲染的组件,则useCallback防止在每次重新渲染组件时重新创建该组件内的回调函数(这意味着该函数组件重新运行)。

    useCallback re-runs only when one of it's dependencies changes.

    useCallback仅在其中一项依赖项更改时才重新运行。

    // in Timer, we are calculating the date and putting it in state a lot
    // this results in a re-render for every state update
    
    // we had a function handleIncrementCount to increment the state 'count'...
    function Timer() {
      const [time, setTime] = React.useState();
      const [count, setCount] = React.useState(0);
    
      // ... but unless we wrap it in useCallback, the function is
      // recreated for every single re-render (bad performance hit)
      // useCallback hook returns a callback that isn't recreated every time
      const inc = React.useCallback(
        function handleIncrementCount() {
          setCount(prevCount => prevCount + 1);
        },
        // useCallback accepts a second arg of a dependencies array like useEffect
        // useCallback will only run if any dependency changes (here it's 'setCount')
        [setCount]
      );
    
      React.useEffect(() => {
        const timeout = setTimeout(() => {
          const currentTime = JSON.stringify(new Date(Date.now()));
          setTime(currentTime);
        }, 300);
    
        return () => {
          clearTimeout(timeout);
        };
      }, [time]);
    
      return (
        <div>
          <p>The current time is: {time}</p>
          <p>Count: {count}</p>
          <button onClick={inc}>+</button>
        </div>
      );
    }

    备注和使用备注 (Memoization and useMemo)

    useMemo is very similar to useCallback and is for improving performance. But instead of being for callbacks, it is for storing the results of expensive calculations.

    useMemo与useCallback非常相似,用于提高性能。 但是,它不是用于回调,而是用于存储昂贵的计算结果。

    useMemo allows us to 'memoize', or remember the result of expensive calculations when they have already been made for certain inputs (we already did it once for these values, so it's nothing new to do it again).

    useMemo允许我们“记忆”,或记住已经为某些输入进行了昂贵的计算的结果(我们已经对这些值进行了一次,因此再做一次并不是什么新鲜事)。

    useMemo returns a value from the computation, not a callback function (but can be a function).

    useMemo从计算中返回一个值,而不是回调函数(但可以是一个函数)。

    // useMemo is useful when we need a lot of computing resources
    // to perform an operation, but don't want to repeat it on each re-render
    
    function App() {
      // state to select a word in 'words' array below
      const [wordIndex, setWordIndex] = useState(0);
      // state for counter
      const [count, setCount] = useState(0);
    
      // words we'll use to calculate letter count
      const words = ["i", "am", "learning", "react"];
      const word = words[wordIndex];
    
      function getLetterCount(word) {
        // we mimic expensive calculation with a very long (unnecessary) loop
        let i = 0;
        while (i < 1000000) i++;
        return word.length;
      }
    
      // Memoize expensive function to return previous value if input was the same
      // only perform calculation if new word without a cached value
      const letterCount = React.useMemo(() => getLetterCount(word), [word]);
    
      // if calculation was done without useMemo, like so:
    
      // const letterCount = getLetterCount(word);
    
      // there would be a delay in updating the counter
      // we would have to wait for the expensive function to finish
    
      function handleChangeIndex() {
        // flip from one word in the array to the next
        const next = wordIndex + 1 === words.length ? 0 : wordIndex + 1;
        setWordIndex(next);
      }
    
      return (
        <div>
          <p>
            {word} has {letterCount} letters
          </p>
          <button onClick={handleChangeIndex}>Next word</button>
          <p>Counter: {count}</p>
          <button onClick={() => setCount(count + 1)}>+</button>
        </div>
      );
    }

    参考和使用参考 (Refs and useRef)

    Refs are a special attribute that are available on all React components. They allow us to create a reference to a given element / component when the component mounts

    引用是一个特殊属性,可在所有React组件上使用。 它们允许我们在安装组件时创建对给定元素/组件的引用

    useRef allows us to easily use React refs. We call useRef (at the top of the component) and attach the returned value to the element's ref attribute to refer to it.

    useRef允许我们轻松使用React refs。 我们调用useRef(在组件顶部),并将返回的值附加到元素的ref属性以引用它。

    Once we create a reference, we use the current property to modify (mutate) the element's properties. Or we can call any available methods on that element (like .focus() to focus an input).

    创建引用后,我们将使用当前属性来修改(变异)元素的属性。 或者,我们可以在该元素上调用任何可用的方法(例如.focus()来使输入集中)。

    function App() {
      const [query, setQuery] = React.useState("react hooks");
      // we can pass useRef a default value
      // we don't need it here, so we pass in null to ref an empty object
      const searchInput = useRef(null);
    
      function handleClearSearch() {
        // current references the text input once App mounts
        searchInput.current.value = "";
        // useRef can store basically any value in its .current property
        searchInput.current.focus();
      }
    
      return (
        <form>
          <input
            type="text"
            onChange={event => setQuery(event.target.value)}
            ref={searchInput}
          />
          <button type="submit">Search</button>
          <button type="button" onClick={handleClearSearch}>
            Clear
          </button>
        </form>
      );
    }

    高级挂钩 (Advanced Hooks)

    上下文和useContext (Context and useContext)

    In React, we want to avoid the following problem of creating multiple props to pass data down two or more levels from a parent component:

    在React中,我们希望避免以下问题:创建多个道具以将数据从父组件向下传递到两个或多个级别:

    // Context helps us avoid creating multiple duplicate props
    // This pattern is also called props drilling:
    function App() {
      // we want to pass user data down to Header
      const [user] = React.useState({ name: "Fred" });
    
      return (
       {/* first 'user' prop */}
        <Main user={user} />
      );
    }
    
    const Main = ({ user }) => (
      <>
        {/* second 'user' prop */}
        <Header user={user} />
        <div>Main app content...</div>
      </>
    );
    
    const Header = ({ user }) => <header>Welcome, {user.name}!</header>;

    Context is helpful for passing props down multiple levels of child components from a parent component.

    上下文有助于将道具从父组件向下传递到多个子组件级别。

    // Here is the previous example rewritten with Context
    // First we create context, where we can pass in default values
    const UserContext = React.createContext();
    // we call this 'UserContext' because that's what data we're passing down
    
    function App() {
      // we want to pass user data down to Header
      const [user] = React.useState({ name: "Fred" });
    
      return (
        {/* we wrap the parent component with the provider property */}
        {/* we pass data down the computer tree w/ value prop */}
        <UserContext.Provider value={user}>
          <Main />
        </UserContext.Provider>
      );
    }
    
    const Main = () => (
      <>
        <Header />
        <div>Main app content...</div>
      </>
    );
    
    // we can remove the two 'user' props, we can just use consumer
    // to consume the data where we need it
    const Header = () => (
      {/* we use this pattern called render props to get access to the data*/}
      <UserContext.Consumer>
        {user => <header>Welcome, {user.name}!</header>}
      </UserContext.Consumer>
    );

    The useContext hook can remove this unusual-looking render props pattern, however, to be able to consume context in whatever function component we like:

    useContext钩子可以删除这种看起来异常的渲染道具模式,以便能够在我们喜欢的任何函数组件中使用上下文:

    const Header = () => {
      // we pass in the entire context object to consume it
      const user = React.useContext(UserContext);
      // and we can remove the Consumer tags
      return <header>Welcome, {user.name}!</header>;
    };

    减速器及使用 (Reducers and useReducer)

    Reducers are simple, predictable (pure) functions that take a previous state object and an action object and return a new state object. For example:

    约简器是简单,可预测(纯)的函数,它们采用先前的状态对象和操作对象并返回新的状态对象。 例如:

    // let's say this reducer manages user state in our app:
    function reducer(state, action) {
      // reducers often use a switch statement to update state
      // in one way or another based on the action's type property
      switch (action.type) {
        // if action.type has the string 'LOGIN' on it
        case "LOGIN":
          // we get data from the payload object on action
          return { username: action.payload.username, isAuth: true };
        case "SIGNOUT":
          return { username: "", isAuth: false };
        default:
          // if no case matches, return previous state
          return state;
      }
    }

    Reducers are a powerful pattern for managing state that is used in the popular state management library Redux (common used with React).

    Reducer是一种流行的状态管理库Redux(与React共同使用)中用于管理状态的强大模式。

    Reducers can be used in React with the useReducer hook in order to manage state across our app, as compared to useState (which is for local component state).

    与useState(用于本地组件状态)相比,Reducer可与useReducer挂钩一起在React中使用,以管理整个应用程序中的状态。

    useReducer can be paired with useContext to manage data and pass it around components easily.

    可以将useReducer与useContext配对使用,以管理数据并轻松地将其传递给组件。

    Thus useReducer + useContext can be an entire state management system for our apps.

    因此useReducer + useContext可以成为我们应用程序的整个状态管理系统。

    const initialState = { username: "", isAuth: false };
    
    function reducer(state, action) {
      switch (action.type) {
        case "LOGIN":
          return { username: action.payload.username, isAuth: true };
        case "SIGNOUT":
          // could also spread in initialState here
          return { username: "", isAuth: false };
        default:
          return state;
      }
    }
    
    function App() {
      // useReducer requires a reducer function to use and an initialState
      const [state, dispatch] = useReducer(reducer, initialState);
      // we get the current result of the reducer on 'state'
    
      // we use dispatch to 'dispatch' actions, to run our reducer
      // with the data it needs (the action object)
      function handleLogin() {
        dispatch({ type: "LOGIN", payload: { username: "Ted" } });
      }
    
      function handleSignout() {
        dispatch({ type: "SIGNOUT" });
      }
    
      return (
        <>
          Current user: {state.username}, isAuthenticated: {state.isAuth}
          <button onClick={handleLogin}>Login</button>
          <button onClick={handleSignout}>Signout</button>
        </>
      );
    }

    编写自定义钩子 (Writing custom hooks)

    Hooks were created to easily reuse behavior between components.

    创建挂钩是为了轻松重用组件之间的行为。

    They're a more understandable pattern than previous ones for class components, such as higher-order components or render props

    对于类组件(例如高阶组件或渲染道具),它们是比以前的模式更易于理解的模式

    What's great is that we can create our own hooks according to our own projects' needs, aside from the ones we've covered that React provides:

    很棒的是,除了我们已经介绍的React提供的那些功能之外,我们还可以根据自己项目的需要创建自己的钩子:

    // here's a custom hook that is used to fetch data from an API
    function useAPI(endpoint) {
      const [value, setValue] = React.useState([]);
    
      React.useEffect(() => {
        getData();
      }, []);
    
      async function getData() {
        const response = await fetch(endpoint);
        const data = await response.json();
        setValue(data);
      };
    
      return value;
    };
    
    // this is a working example! try it yourself (i.e. in codesandbox.io)
    function App() {
      const todos = useAPI("https://todos-dsequjaojf.now.sh/todos");
    
      return (
        <ul>
          {todos.map(todo => <li key={todo.id}>{todo.text}</li>}
        </ul>
      );
    }

    钩子规则 (Rules of hooks)

    There are two core rules of using React hooks that we cannot violate for them to work properly:

    使用React挂钩有两个我们不能违反的核心规则,它们才能正常工作:

    1. Hooks can only be called at the top of components (they cannot be in conditionals, loops or nested functions)

      挂钩只能在组件的顶部调用(它们不能在条件,循环或嵌套函数中)
    2. Hooks can only be used within function components (they cannot be in normal JavaScript functions or class components)

      挂钩只能在函数组件内使用(不能在常规JavaScript函数或类组件中使用)
    function checkAuth() {
      // Rule 2 Violated! Hooks cannot be used in normal functions, only components
      React.useEffect(() => {
        getUser();
      }, []);
    }
    
    function App() {
      // this is the only validly executed hook in this component
      const [user, setUser] = React.useState(null);
    
      // Rule 1 violated! Hooks cannot be used within conditionals (or loops)
      if (!user) {
        React.useEffect(() => {
          setUser({ isAuth: false });
          // if you want to conditionally execute an effect, use the
          // dependencies array for useEffect
        }, []);
      }
    
      checkAuth();
    
      // Rule 1 violated! Hooks cannot be used in nested functions
      return <div onClick={() => React.useMemo(() => doStuff(), [])}>Our app</div>;
    }

    下一步是什么 (What's Next)

    There are many other React concepts to learn, but these are the ones I believe you must know before any others to set you on the path to React mastery in 2020.

    还有许多其他的React概念需要学习,但我相信您必须先了解这些概念,才能使您踏上2020年的React掌握道路。

    Want a quick reference of all of these concepts?

    是否需要所有这些概念的快速参考?

    Download a complete PDF cheatsheet of all this info right here.

    在此处下载所有这些信息的完整PDF速查表。

    Keep coding and I'll catch you in the next article!

    继续编码,我将在下一篇文章中帮助您!

    想要成为JS大师吗? 加入2020年JS训练营 (Want To Become a JS Master? Join the 2020 JS Bootcamp )

    Join the 2020 JS Bootcamp

    Follow + Say Hi! 👋 Twittercodeartistry.io

    关注+说声嗨! 👋 Twitter的codeartistry.io

    翻译自: https://www.freecodecamp.org/news/the-react-cheatsheet-for-2020/

    react 示例

    展开全文
  • react示例大全

    2018-09-12 15:51:03
    学习react十三天,每天一个demo,从基础开始,到熟悉使用react
  • React示例demo

    2018-09-04 09:49:28
    React 一个简单的demo 适合初学者---主要包括环境配置webpack 使用,热更新等
  • react高阶函数 科技术语系列 (Tech Jargon series) There are so many phrases that get thrown around at tech meetups and conferences, assuming that everyone is already down with the lingo. I’m often not ...

    react高阶函数

    科技术语系列 (Tech Jargon series)

    There are so many phrases that get thrown around at tech meetups and conferences, assuming that everyone is already down with the lingo. I’m often not down with the lingo. It’s common for developers to act astonished that I lack a piece of knowledge.

    假设每个人都已经对这种术语感到沮丧,那么在技术聚会和会议上会出现很多短语。 我常常不喜欢行话。 开发人员惊讶地发现我缺乏知识,这很常见。

    The truth is, I often just don’t know the right word for it. As humans, but especially developer humans, we love to dismiss those who don’t “talk the talk”, so this series is about getting a solid understanding of programming concepts that one “should know”.

    事实是,我常常只是不知道正确的词。 作为人类,尤其是开发人员,我们喜欢解雇那些不“谈论”的人,因此本系列文章旨在对人们“应该知道”的编程概念有扎实的理解。

    My first topic for this series is Higher-Order Functions. I was at a tech meetup the other day, and we were discussing React and how difficult it can be for React newbies to get into the code. I mentioned that higher-order components (HOCs) can be tough to understand. A response was that they are much like higher-order functions, don’t I agree? And I said: “I don’t know what that is.” When I asked for an example, I was told “map”. I made a joke about how I have no idea what “map” is and we moved on.

    本系列的第一个主题是高阶函数。 前几天我在一次技术聚会上,我们在讨论React以及React新手进入代码有多困难。 我提到过高阶组件(HOC)可能很难理解。 有人回答说它们很像高阶函数,我不同意吗? 我说:“我不知道那是什么。” 当我问一个例子时,我被告知“地图”。 我开玩笑说我不知道​​什么是“地图”,我们继续前进。

    But still: what is a higher-order function?

    但仍然: 什么是高阶函数?

    (Note: all the examples given are in Javascript, but this concept applies to every programming language.)

    (注意:给出的所有示例均使用Javascript,但是此概念适用于每种编程语言。)

    高阶函数:定义 (Higher-order functions: a definition)

    A higher-order function is one which either a) takes a function as an argument or b) returns a function.

    高阶函数是a)将函数作为参数或b)返回函数的函数。

    If a function doesn’t do either of those things, it is a first-order function.

    如果一个函数不做任何事情,那么它就是一阶函数

    地图 (Map)

    Let’s start with the example I was given: map.

    让我们从给出的示例开始: map

    [1, 2, 3].map(num => num * 2)> [2, 4, 6]

    The map function is called on an array and takes a “callback” function. It applies the function to each of the items in the array, returning a new array. [1, 2, 3] is our array and num => num * 2 is our function. A callback is the function argument passed to our higher-order function.

    map函数在数组上调用,并采用“回调”函数。 它将函数应用于数组中的每个项目,并返回一个新数组。 [1, 2, 3]是我们的数组, num => num * 2是我们的函数。 回调是传递给我们的高阶函数的函数参数。

    This HOF is baked into the language, prototyped on Array (Array.prototype.map).

    此HOF融入了该语言,并在Array( Array.prototype.map )上原型化。

    Other examples of HOFs prototyped on Array are filter, reduce, and some.

    在Array上原型化的HOF的其他示例包括filterreducesome

    自订范例 (Custom example)

    So let’s write our own higher-order function.

    因此,让我们编写我们自己的高阶函数。

    通过功能 (Passed function)

    const myFunc = age => age * 2

    高阶函数 (Higher-order function)

    Now we write a function that takes in a function.

    现在,我们编写一个接受函数的函数。

    const hof = (customFunc, age) => customFunc(age + 5)

    We’ll pass a number to hof, which will add 5 and then call our passed function, which will double it. If we pass 10, we pass 15 to our first function, which then doubles to 30.

    我们将一个数字传递给hof ,该数字将加5,然后调用传递的函数,该函数会将其加倍。 如果传递10,则将15传递给第一个函数,然后将其加倍为30。

    使用React“组件”的自定义示例 (Custom example with React “components”)

    As I noted above, this topic came up in reference to React’s components. As a React component is a function, when passing it to another function, we are creating our own higher-order function, which React calls “higher-order components”. If you are using stateful components (and extending React’s Component), you are already using HOCs.

    正如我上面提到的,这个主题是参考React的组件提出的。 作为一个React组件是一个函数,当将其传递给另一个函数时,我们正在创建自己的高阶函数,React称之为“高阶组件”。 如果您正在使用有状态组件(并扩展了React的Component ),那么您已经在使用HOC。

    无状态组件 (Stateless Component)

    const details = ({ name, randomNum }) =>
      `${name}, ${randomNum}`

    We have a function, called details, into which we pass props. We are deconstructing them as they come in and assigning them to local variables name and randomNum. This is ES6 syntax — if it looks unfamiliar give it a google (you’ll love it).

    我们有一个称为details的函数,我们可以在其中传递props 。 当它们进入时,我们正在对其进行解构,并将它们分配给局部变量namerandomNum 。 这是ES6语法-如果看起来不熟悉,请给它一个google(您会喜欢的)。

    This is a first-order function — it takes one argument (a props object) and returns a template literal.

    这是一阶函数 -它接受一个参数( props对象)并返回模板文字。

    高阶分量 (Higher-order component)

    const hoc = (component, props) => {
      const randomNum = Math.floor(Math.random() * 100)
      return component({ ...props, randomNum })
    }

    This is a higher-order function — it takes in a function (the component, which it then calls, passing in additional props). This is an extremely basic example of what every stateless React component is doing.

    这是一个高阶函数 -它接受一个函数(然后调用的component ,传入其他props)。 这是每个无状态React组件正在做什么的极其基本的示例。

    You can employ this pattern to abstract code that is shared among many components in your application.

    您可以使用此模式来抽象在应用程序中许多组件之间共享的代码。

    Are you wondering if you can nest higher-order functions? You can! But be careful. Abstractions should make code easier to read and work with. It’s easy to get down a path here where your code is so obtuse no one can figure out how to do anything.

    您是否想知道是否可以嵌套高阶函数? 您可以! 但小心点。 抽象应该使代码更易于阅读和使用 。 在您的代码如此晦涩难懂的地方很容易走到一条路,没人能弄清楚怎么做。

    参考文献 (References)

    翻译自: https://www.freecodecamp.org/news/higher-order-functions-what-they-are-and-a-react-example-1d2579faf101/

    react高阶函数

    展开全文
  • 学习ReactNative示例

    2019-08-10 06:05:00
    学习React-Native示例
  • react的脚手架示例
  • React Native 示例App(NavigatorEX, Redux, Facebook, Analytics SDKs, Etc)
  • React Mobx示例

    2020-04-26 11:41:21
    import React from 'react'; import ReactDOM from 'react-dom'; import { observable, computed, useStrict, action } from 'mobx'; import App from './App'; import * as serviceWorker from './servi...
  • 一个使用redux的简单react native示例
  • 运行ReactNative示例

    千次阅读 2015-10-31 17:39:23
    既然感觉ReactNative开发靠谱, 那么我们就来看看ReactNative都能做...Github: https://github.com/facebook/react-native内容很多, 包含一些依赖库和示例(Example), 下载的有点慢, 耐心等待.下载完成后, 在react-nati
  • React Loadable示例项目
  • react redux入门示例

    2020-08-27 16:24:36
    本篇文章主要介绍了react redux入门示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • react native 示例代码

    2018-12-07 23:03:00
    https://react.rocks/tag/ReactNative?show=60 https://github.com/ReactNativeNews/React-Native-Apps 转载于:https://www.cnblogs.com/honeynm/p/10085750.html
  • react完整示例 尖端技术的完美React应用程序 介绍 每个开发人员都可以在网上搜索并找到基于React与Web应用程序相关的内容,并查看一些实现示例。 一些概念,例如: 服务器端渲染 使用React Router 使用...
  • 主要介绍了react使用CSS实现react动画功能,结合实例形式分析了react使用CSS实现react动画功能具体步骤与实现方法,需要的朋友可以参考下
  • 摘要: React示例教程。 原文:快速了解 React Hooks 原理 译者:前端小智 到 React 16.8 目前为止,如果编写函数组件,然后遇到需要添加状态的情况,咱们就必须将组件转换为类组件。 编写 class Thing extends ...
  • react-navigation示例

    千次阅读 2017-06-27 15:15:10
    react-navigation示例什么react-navigation (官网:https://reactnavigation.org/docs/intro/) 在react-navigation出来之前,页面跳转最多使用的是navigator,然而navigator最大的缺点就是卡顿!卡顿!卡顿!以至于你...
  • google-map-react-examples, google地图响应组件的示例 google-map-react示例这个项目是同构的Flummox 怀旧应用程序带有 google-map-react控件示例。它还使用了非标准的方法来。其他文档。isomorphic.md安装我强烈...
  • React Conf 2018 "Moving to Suspense" 示例源代码
  • 网易云音乐 react服务端渲染示例

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,419
精华内容 967
关键字:

react示例