天天看點

13個React代碼片段彙總

13個React代碼片段彙總

英文 | https://medium.com/frontend-canteen/a-summary-of-react-by-10-code-snippets-15aca7c5a8c8

01、Create React App ​

$ create-react-app YOUR_APP_NAME      

Create React App 是一個用于建立 React 項目的 CLI。

02、JSX

const element = <h1>Hello, world!</h1>;      

我們可以通過 JSX 在 JavaScript 中編寫 HTML。

03、在 JSX 中嵌入表達式

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;      

隻需使用 {} 來包裝 JavaScript 表達式。

04、建立一個元件

import React from 'react'


const Hello = () => <div>Hello World</div>


export default Hello      

它是一個簡單的、無狀态的、功能性的元件。

05、建立類元件

import React from 'react'


class Hello extends React.Component {
  render() {
    return <div>Hello World</div>
  }
}


export default Hello      

06、将值傳遞給元件

const User = ({name, email}) => {
    <div>
      <div> name: {name} </div>
      <div> email: {email} </div>
    </div>
}


export default User      

用法:

<User name="Jon" age="35">      

07、元件嵌套

const Child = (props) => (
  <div>{props.message}</div>
)


const Father = () => (
  return (<div>
    <div> I am father</div>
    <Child message="aaa"></Child>
  </div>)
)      

08、向元件添加狀态

import { useState } from "react";


export default function Counter(){
    // Declare a new state variable, which we'll call "count"
  let [count, setCount] = useState(0)


  return <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}> add</button>
    </div>
}      

09、聲明多個狀态變量

當然,我們可以使用 useStates 定義多個狀态。

function ManyStates() {
  // Declare multiple state variables!
  const [name, setName] = useState('');
  const [age, setAge] = useState(0);
  const [todos, setTodos] = useState([{ text: 'Eat' }]);
  // ...
}      

10、使用效果

import React, { useState, useEffect } from 'react';


function Example() {
  const [count, setCount] = useState(0);


  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });


  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}      

11、處理事件

function Form() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log('You clicked submit.');
  }


  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}      

12、條件渲染

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}      

用法:

<Greeting isLoggedIn={false} />      

13、清單元件

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li>{number}</li>
  );
  return (
    <ul>{listItems}</ul>
  );
}      

用法:

<NumberList numbers={[1, 2, 3, 4, 5]} />)      

總結

以上就是我今天分享的13個關于React的代碼片段,希望這個對你有幫助。

感謝您的閱讀,祝程式設計愉快!

13個React代碼片段彙總

繼續閱讀