react示例_最好的React示例

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示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值