React -前端组件及个例

JSX

  1. basic format of JSX
  • Basic JSX component
const JSX = (
  <div>
    <h1>Hello World</h1>
    <p>Lets render this to the DOM</p>
  </div>
);
  • Define an HTML Class in JSX
    In React, there is className instead of class used in defining a HTML element.
const JSX = (
  <div className='myDiv'>
    <h1>Add a class to this div</h1>
  </div>
);
  • Another important way is in the idea of the self-closing tag.

In HTML, almost all tags have both an opening and closing tag:

; the closing tag always has a forward slash before the tag name that you are closing. However, there are special instances in HTML called “self-closing tags”, or tags that don’t require both an opening and closing tag before another tag can start.

For example the line-break tag can be written as <br> or as <br />, but should never be written as <br></br>, since it doesn’t contain any content.

In JSX, the rules are a little different. Any JSX element can be written with a self-closing tag, and every element must be closed. The line-break tag, for example, must always be written as <br /> in order to be valid JSX that can be transpiled. A <div>, on the other hand, can be written as <div /> or <div></div>. The difference is that in the first syntax version there is no way to include anything in the <div />. You will see in later challenges that this syntax is useful when rendering React components.

ReactDOM

ReactDOM offers a simple method to render React elements to the DOM which looks like this: ReactDOM.render(componentToRender, targetNode), where the first argument is the React element or component that you want to render, and the second argument is the DOM node that you want to render the component to.

const JSX = (
  <div>
    <h1>Hello World</h1>
    <p>Lets render this to the DOM</p>
  </div>
);
// Add your code below this line
// const element = document.getElementById("challenge-node")
ReactDOM.render(JSX, document.getElementById("challenge-node"));

Create a React component (one HTML element)

  1. Use a JavaScript function.
    Defining a component in this way creates a stateless functional component. For now, think of a stateless component as one that can receive data and render it, but does not manage or track changes to that data.

Note: React requires your function name to begin with a capital letter.
Example:

const DemoComponent = function() {
  return (
    <div className='customClass' />
  );
};
  1. With the ES6 class syntax.
    In the following example, Kitten extends React.Component:
class Kitten extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>Hi</h1>
    );
  }
}

Kitten class has a constructor defined within it that calls super(). It uses super() to call the constructor of the parent class, in this case React.Component.

Create a Component with Composition (t/m HTML element)

const ChildComponent = () => {
  return (
    <div>
      <p>I am the child</p>
    </div>
  );
};

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>I am the parent</h1>
        <ChildComponent />
      </div>
    );
  }
};

This should illustrate the parent/child component between the ParentComponent and the ChildComponent.

Render a Class Component to the DOM

class TypesOfFood extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>Types of Food:</h1>
        {/* Change code below this line */}
        <Fruits/>
        <Vegetables/>

        {/* Change code above this line */}
      </div>
    );
  }
};

// Change code below this line

ReactDOM.render(<TypesOfFood/>, document.getElementById("challenge-node"))

总结:
JSX、ReactDOM 和 React 的关系

  1. JSX (JavaScript XML):

    • JSX 是一种 JavaScript 语法扩展,它允许我们在 JavaScript 代码中编写类似 HTML 的代码结构。
    • JSX 让 React 组件的编写更加直观和易读,并且使得组件的结构更加清晰。
    • JSX 最终会被转译为普通的 JavaScript 函数调用,这些函数调用会创建 React 元素树。
  2. ReactDOM:

    • ReactDOM 是 React 的官方 DOM 操作库,用于将 React 组件渲染到浏览器中的 DOM 中。
    • ReactDOM 提供了一些方法,例如 ReactDOM.render(),它接受一个 React 元素并将其渲染到指定的 DOM 节点中。
  3. React 组件:

    • React 组件是构建 React 应用程序的基本单位,它是可复用的、独立的代码块,用于封装特定的功能。
    • React 组件可以是类组件(class components)或函数组件(function components)。
    • 在 JSX 中,使用 React 组件的语法类似 HTML 标签,例如 <MyComponent />,其中 MyComponent 是一个自定义的 React 组件。

关系总结:

  • JSX 用于编写 React 组件的结构,使得代码编写更加直观易懂。
  • ReactDOM 用于将 JSX 表示的 React 组件渲染到浏览器中的 DOM 中。
  • React 组件可以通过 JSX 表达,然后由 ReactDOM 渲染到页面上。

JSX、ReactDOM 和 React 组件之间的关系的例子

  1. JSX 示例:
const element = <h1>Hello, world!</h1>;

在上面的代码中,<h1>Hello, world!</h1> 就是一个 JSX 元素,它类似于 HTML,但实际上是 JavaScript 代码。

  1. React 组件示例:
// 函数组件
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// 类组件
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

在上面的代码中,Welcome 是一个 React 组件,可以作为一个函数或类来定义。这里使用了 JSX 语法来表示组件的结构。

  1. ReactDOM 示例:
// 使用 ReactDOM 渲染一个 React 组件到 HTML 页面中
const element = <Welcome name="Alice" />;
ReactDOM.render(element, document.getElementById('root'));

在上面的代码中,我们使用了 ReactDOM.render() 方法将一个 React 组件(使用 JSX 表示)渲染到了页面上的根元素中。其中ReactDOM.render(<componentToRender/>, targetNode)

综合起来,JSX 允许我们以类似 HTML 的语法编写 React 组件,ReactDOM 则负责将这些 JSX 表示的组件渲染到浏览器中的 DOM 中。

Pass Props to a Stateless Functional Component

In React, you can pass props, or properties, to child components. Say you have an App component which renders a child component called Welcome which is a stateless functional component. You can pass Welcome a user property by writing:

<App>
	<Welcome user='Mark' />
</App>

For example:

const CurrentDate = (props) => {
  return (
    <div>
      { /* Change code below this line */ }
      <p>The current date is: {props.date}</p>
      { /* Change code above this line */ }
    </div>
  );
};

class Calendar extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h3>What date is it?</h3>
        
        <CurrentDate date={Date()}/>
        
      </div>
    );
  }
};

When rendering CurrentDate from the Calendar component, pass in a property of date assigned to the current date from JavaScript’s Date object. Then access this prop in the CurrentDate component, showing its value within the p tags.

Pass an Array as Props to components

const List = (props) => {
  return <p>{props.tasks.join(',')}</p>

};

class ToDo extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>To Do Lists</h1>
        <h2>Today</h2>
        <List tasks = {["walk dog", "workout", "laudry"]} />
        <h2>Tomorrow</h2>
        <List tasks = {["walk dog", "workout", "dinner"]} />
        
      </div>
    );
  }
};

Use Default Props to component

The ability to set default props is a useful feature in React.

const ShoppingCart = (props) => {
  return (
    <div>
      <h1>Shopping Cart Component</h1>
    </div>
  )
};
// Change code below this line
ShoppingCart.defaultProps = { items: 0 }

Override Default Props

const Items = (props) => {
  return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
}

Items.defaultProps = {
  quantity: 0
}

class ShoppingCart extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    { /* Change code below this line */ }
    return <Items quantity = {10}/>
    { /* Change code above this line */ }
  }
};

Parent/child components props

从一个class类(父)中复用其参数到另一个class类(子),需要使用 this.props.property

// parent
class App extends React.Component {
  constructor(props) {
    super(props);

  }
  render() {
    return (
        <div>
            <Welcome name = "this is name"/>
        </div>
    );
  }
};
// child
class Welcome extends React.Component {
  constructor(props) {
    super(props);

  }
  render() {
    return (
        <div>
          <p>Hello, <strong>{this.props.name}</strong>!</p>
        </div>
    );
  }
};

Function state

A stateless functional component is any function you write which accepts props and returns JSX. A stateless component, on the other hand, is a class that extends React.Component, but does not use internal state (covered in the next challenge). Finally, a stateful component is a class component that does maintain its own internal state. You may see stateful components referred to simply as components or React components.

// parent
class CampSite extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <Camper/>
      </div>
    );
  }
};

// child
class Camper extends React.Component {
  render() {
    const { name } = this.props;
    return (
      <div>
        <p>{name}</p>
      </div>
    );
  }
}

// Same results but different parttern
class Camper extends React.Component {
  render() {
    // const { name } = this.props;
    return (
      <div>
        <p>{this.props.name}</p>
      </div>
    );
  }
}

Camper.defaultProps = {
  name: 'CamperBot'
};

Camper.propTypes = {
  name: PropTypes.string.isRequired
};

Create a Stateful Component

One of the most important topics in React is state. State consists of any data your application needs to know about, that can change over time. You want your apps to respond to state changes and present an updated UI when necessary. React offers a nice solution for the state management of modern web applications.

You create state in a React component by declaring a state property on the component class in its constructor. This initializes the component with state when it is created. The state property must be set to a JavaScript object. Declaring it looks like this:

this.state = {

}

You have access to the state object throughout the life of your component. You can update it, render it in your UI, and pass it as props to child components.


class StatefulComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: "jojo"
    }
  }
  render() {
    return (
      <div>
        <h1>{this.state.firstName}</h1>
      </div>
    );
  }
};

Render State - Method 1 (Declare directly)

Declare the state directly.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'freeCodeCamp'
    }
  }
  render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

Render State - Method 2 (Declare in a component first)

Declare the state in a component and then invoke the component.

In the render() method, before the return statement, you can write JavaScript directly.

For example, you could declare functions, access data from state or props, perform computations on this data, and so on. Then, you can assign any data to variables, which you have access to in the return statement.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'freeCodeCamp'
    }
  }
  render() {
    const name = this.state.name;
    return (
      <div>
        <h1>{name}</h1>
      </div>
    );
  }
};

Bind ‘this’ to a Class Method (handleClick)

The line this.handleClick = this.handleClick.bind(this); in the constructor is used to bind the context of the handleClick method to the component instance. Without this binding, when handleClick is called in response to the click event, this within the method would refer to the event target, not the component instance.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello"
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({
      text: "You clicked!"
    });
  }
  render() {
    return (
      <div>
        <button onClick = {this.handleClick} >Click Me</button>
        <h1>{this.state.text}</h1>
      </div>
    );
  }
};

The flow of the code above:

  1. The user clicks the button.
  2. The onClick event handler associated with the button calls the handleClick method.
  3. Inside the handleClick method, setState() is called to update the component’s state.
  4. React detects the state update and schedules a re-render of the component.
  5. The component is re-rendered with the updated state, causing the UI to reflect the new state (in this case, displaying “You clicked!”).

Use State to Toggle an Element

The function on how to change the state of the target element.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibility: false
    };
    this.toggleVisibility = this.toggleVisibility.bind(this);
  }
  toggleVisibility(){
    this.setState(state => {
      if (state.visibility === true) {
         return { visibility: false };
       } else {
         return { visibility: true };
      }
    });
  }
  render() {
    if (this.state.visibility) {
      return (
        <div>
          <button onClick={this.toggleVisibility}>Click Me</button>
          <h1>Now you see me!</h1>
        </div>
      );
    } else {
      return (
        <div>
          <button onClick={this.toggleVisibility}>Click Me</button>
        </div>
      );
    }
  }
}

A React class component called MyComponent. Here’s a breakdown to it:

  1. Class Component Definition:

    • The component is defined using the class keyword, which creates a new class called MyComponent.
    • It extends React.Component, which is a base class for React components.
  2. Constructor:

    • The constructor method is called when an instance of the component is created.
    • It receives props as a parameter and calls super(props) to call the constructor of the parent class (React.Component) with the same props.
    • Inside the constructor, it initializes the component’s state with { visibility: false }.
  3. State Management:

    • The component has a state variable called visibility which determines whether a certain element should be visible or not.
  4. Event Handling:

    • There’s a method called toggleVisibility which toggles the visibility state between true and false.
    • This method is bound to the class instance using this.toggleVisibility = this.toggleVisibility.bind(this) in the constructor. This ensures that this refers to the component instance within the method.
  5. Rendering:

    • The render method returns JSX based on the current state.
    • If visibility is true, it renders a <div> with a button and an <h1> element.
    • If visibility is false, it renders a <div> with just a button.
    • Both buttons have an onClick event handler that calls the toggleVisibility method when clicked.
  6. Conditional Rendering:

    • The rendering logic inside render method is conditional based on the value of visibility.

In summary, this component toggles the visibility of an element when a button is clicked. It demonstrates the use of state management, event handling, and conditional rendering in a React class component.

Write a Simple Counter

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
    this.reset = this.reset.bind(this);

  }
    increment(){
      this.setState((state) =>({
        count: state.count+1
      }));
    }
    decrement(){
      this.setState((state) =>({
      count: state.count - 1
      }));
    }
    reset() {
     this.setState({
      count: 0
    });
    }
  render() {
    return (
      <div>
        <button className='inc' onClick={this.increment}>Increment!</button>
        <button className='dec' onClick={this.decrement}>Decrement!</button>
        <button className='reset' onClick={this.reset}>Reset</button>
        <h1>Current Count: {this.state.count}</h1>
      </div>
    );
  }
};

在这个例子中,需要注意的语法有:

// 1. Bind the Function with this
this.function = this.function.bind(this);

// 2. Define a function with this.setState()
increment(){
      this.setState((state) =>({
        count: state.count+1
      }));
    }
//3. invoke a function
<button className='inc' onClick={this.increment}>Increment!</button>

Create a Controlled Input

class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    this.handleChange = this.handleChange.bind(this);
    
  }
  handleChange(event){
    this.setState(()=>({
      input: event.target.value,

    }))
  }
  render() {
    return (
      <div>
       <input value = {this.state.input} onChange={this.handleChange} />

        
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};

Create a Controlled Form

In React, the onChange event is a synthetic event that occurs when the value of an , , or element is changed by the user.

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      submit: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({
      input: event.target.value
    });
  }
  handleSubmit(event) {
    event.preventDefault();
    this.setState({
      submit: this.state.input
    });

  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
        <input
            value={this.state.input}
            onChange={this.handleChange} />
          <button type='submit'>Submit!</button>
        </form>
        <h1>{this.state.submit}</h1>
       
      </div>
    );
  }
}

The flow of the code in the MyForm component is as follows:

  1. Initialization: When the MyForm component is mounted, the constructor is called. In the constructor:

    • The initial state is set with an empty input and submit values.
    • Event handler methods handleChange and handleSubmit are bound to the component instance using .bind(this).
  2. Input Change: When the user types into the input field, the onChange event is triggered. This calls the handleChange method.

    • handleChange updates the component’s state with the new value entered by the user in the input field.
  3. Form Submission: When the user submits the form (by clicking the Submit button or pressing Enter), the onSubmit event is triggered. This calls the handleSubmit method.

    • handleSubmit prevents the default form submission behavior using event.preventDefault().
    • It updates the submit state with the current value of input.
  4. Re-render: After the state is updated in either handleChange or handleSubmit, the render method is called.

    • The input field reflects the current value of input state.
    • The form has a onSubmit event listener attached to it, so when the form is submitted, it calls handleSubmit.
    • The h1 element displays the value of submit state, which is updated after form submission.
  5. User Interaction: The user can continue typing into the input field and submitting the form, triggering the handleChange and handleSubmit methods respectively, and updating the component’s state accordingly.

This flow ensures that the input field reflects the current value of input state, and the submit state is updated with the value entered by the user when the form is submitted. Finally, the submitted value is displayed below the form.

Pass State as Props to Child Components

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'CamperBot'
    }
  }
  render() {
    return (
       <div>
         <Navbar name ={this.state.name} />
       </div>
    );
  }
};

class Navbar extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
    <div>
      {/* Change code below this line */}
      <h1>Hello, my name is:{this.props.name} </h1>
      {/* Change code above this line */}
    </div>
    );
  }
};

In parent component, it initializes the state with a name property set to ‘CamperBot’. The name state passed as a prop to <NavBar />.

The flow of the above code:

  1. MyApp Component:

    • This component is a class component.
    • It has a constructor that initializes the state with a name property set to ‘CamperBot’.
    • The render method returns JSX that includes a Navbar component with the name state passed as a prop.
  2. Navbar Component:

    • This component is also a class component.
    • It receives props in its constructor but doesn’t do anything with them.
    • The render method returns JSX with an <h1> element that displays the name passed as a prop (this.props.name).
  3. Flow of Execution:

    • When MyApp is rendered, it includes a Navbar component as its child.
    • The Navbar component receives the name prop from its parent (MyApp).
    • Inside the Navbar component’s render method, the value of name is accessed using this.props.name.
    • The name is then displayed within an <h1> element in the rendered output.
    • So, the output would be: “Hello, my name is: CamperBot”.

In summary, the MyApp component initializes the state with a name, and then passes that name as a prop to the Navbar component, which renders a greeting message including the name.

Convey the callbacks as props

Use the Lifecycle Method componentWillMount

React components have several special methods that provide opportunities to perform actions at specific points in the lifecycle of a component. These are called lifecycle methods, or lifecycle hooks, and allow you to catch components at certain points in time. This can be before they are rendered, before they update, before they receive props, before they unmount, and so on. Here is a list of some of the main lifecycle methods: componentWillMount() componentDidMount() shouldComponentUpdate() componentDidUpdate() componentWillUnmount()

Use the Lifecycle Method componentDidMount

Most web developers, at some point, need to call an API endpoint to retrieve data. If you’re working with React, it’s important to know where to perform this action.

The best practice with React is to place API calls or any calls to your server in the lifecycle method componentDidMount(). This method is called after a component is mounted to the DOM. Any calls to setState() here will trigger a re-rendering of your component. When you call an API in this method, and set your state with the data that the API returns, it will automatically trigger an update once you receive the data.


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeUsers: null
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({
        activeUsers: 1273
      });
    }, 2500);
  }
  render() {
    return (
      <div>
        {/* Change code below this line */}
        <h1>Active Users: {this.state.activeUsers}</h1>
        {/* Change code above this line */}
      </div>
    );
  }
}

Add Event Listeners with componentDidMount

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: ''
    };
    this.handleEnter = this.handleEnter.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  // Change code below this line
  componentDidMount(keydown) {
    document.addEventListener("keydown", this.handleKeyPress)


  }
  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleKeyPress)

  }
  // Change code above this line
  handleEnter() {
    this.setState((state) => ({
      message: state.message + 'You pressed the enter key! '
    }));
  }
  handleKeyPress(event) {
    if (event.keyCode === 13) {
      this.handleEnter();
    }
  }
  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    );
  }
};

Optimize Re-Renders with shouldComponentUpdate

So far, if any component receives new state or new props, it re-renders itself and all its children. This is usually okay. But React provides a lifecycle method you can call when child components receive new state or props, and declare specifically if the components should update or not. The method is shouldComponentUpdate(), and it takes nextProps and nextState as parameters.

This method is a useful way to optimize performance. For example, the default behavior is that your component re-renders when it receives new props, even if the props haven’t changed. You can use shouldComponentUpdate() to prevent this by comparing the props. The method must return a boolean value that tells React whether or not to update the component. You can compare the current props (this.props) to the next props (nextProps) to determine if you need to update or not, and return true or false accordingly.

shouldComponentUpdate(nextProps, nextState) {
    console.log('Should I update?');
    if (nextProps.value % 2 == 0) {
        return true;
      }
  }

Render with an If-Else Condition

Another application of using JavaScript to control your rendered view is to tie the elements that are rendered to a condition. When the condition is true, one view renders. When it’s false, it’s a different view. You can do this with a standard if/else statement in the render() method of a React component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: true
    }
    this.toggleDisplay = this.toggleDisplay.bind(this);
  }
  toggleDisplay() {
    this.setState((state) => ({
      display: !state.display
    }));
  }
  render() {
    // Change code below this line
    if (this.state.display){
      return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         <h1>Displayed!</h1>
       </div>
    );
    }else {
      return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
       </div>
    );

    }
    
  }
};

Use && for a More Concise Conditional

you can use the && logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is true, and if it is, return some markup. Here’s an example:

{condition && <p>markup</p>}

render() {
    // Change code below this line
    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         {this.state.display && <h1>Displayed!</h1>}

       </div>
    );
  }
};

Use a Ternary Expression for Conditional Rendering

condition ? expressionIfTrue : expressionIfFalse;

Display different buttons when in different conditions.

const inputStyle = {
  width: 235,
  margin: 5
};

class CheckUserAge extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userAge: '',
      input: ''
    }
    this.submit = this.submit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(e) {
    this.setState({
      input: e.target.value,
      userAge: ''
    });
  }
  submit() {
    this.setState(state => ({
      userAge: state.input
    }));
  }
  render() {
    const buttonOne = <button onClick={this.submit}>Submit</button>;
    const buttonTwo = <button>You May Enter</button>;
    const buttonThree = <button>You Shall Not Pass</button>;
    return (
      <div>
        <h3>Enter Your Age to Continue</h3>
        <input
          style={inputStyle}
          type='number'
          value={this.state.input}
          onChange={this.handleChange}
        />
        <br />
       {this.state.userAge =='' 
       ? buttonOne 
       : this.state.userAge >= 18 
       ? buttonTwo
       : buttonThree}
      </div>
    );
  }
}

Render Conditionally from Props

class Results extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    
    
    return <h1>{this.props.fiftyFifty ? "You Win!" : "You Lose!"}</h1>;
    {/* Change code above this line */}
  }
}

class GameOfChance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 1
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(prevState => {
      // Complete the return statement:
      return {
        counter: prevState.counter+1
      }
    });
  }
  render() {
    const expression = Math.random() >= 0.5; // Change this line
    return (
      <div>
        <button onClick={this.handleClick}>Play Again</button>
        <Results fiftyFifty={expression} />

        <p>{'Turn: ' + this.state.counter}</p>
      </div>
    );
  }
}

Use Array.map() to Dynamically Render Elements

When the components need to be rendered an unknown number of elements

const textAreaStyles = {
  width: 235,
  margin: 5
};

class MyToDoList extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      userInput : '',
      toDoList : []

    }
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  handleSubmit() {
    const itemsArray = this.state.userInput.split(',');
    this.setState({
      toDoList: itemsArray
    });
  }
  handleChange(e) {
    this.setState({
      userInput: e.target.value
    });
  }
  render() {
    const items = this.state.toDoList.map(i => <li>{i}</li>); // Change this line
    return (
      <div>
        <textarea
          onChange={this.handleChange}
          value={this.state.userInput}
          style={textAreaStyles}
          placeholder='Separate Items With Commas'
        />
        <br />
        <button onClick={this.handleSubmit}>Create List</button>
        <h1>My "To Do" List:</h1>
        <ul>{items}</ul>
      </div>
    );
  }
}

Give Sibling Elements a Unique Key Attribute

When you create an array of elements, each one needs a key attribute set to a unique value. React uses these keys to keep track of which items are added, changed, or removed. This helps make the re-rendering process more efficient when the list is modified in any way.

Note: Keys only need to be unique between sibling elements, they don’t need to be globally unique in your application.

const frontEndFrameworks = [
  'React',
  'Angular',
  'Ember',
  'Knockout',
  'Backbone',
  'Vue'
];

function Frameworks() {
  const renderFrameworks = frontEndFrameworks.map(item => <li key={item}>{item}</li>); // Change this line
// Other key value
//  const renderFrameworks = frontEndFrameworks.map(item => <li key={index}>{item}</li>); // Change this line
  return (
    <div>
      <h1>Popular Front End JavaScript Frameworks</h1>
      <ul>
        {renderFrameworks}
      </ul>
    </div>
  );
};

Use Array.filter() to Dynamically Filter an Array

Another method related to map is filter, which filters the contents of an array based on a condition, then returns a new array. For example, if you have an array of users that all have a property online which can be set to true or false, you can filter only those users that are online by writing:

let onlineUsers = users.filter(user => user.online);
  • 15
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值