美文网首页
一文加强对React的记忆(2021 年 6 月更新),收藏再也

一文加强对React的记忆(2021 年 6 月更新),收藏再也

作者: DOVEW张礼奎 | 来源:发表于2021-06-14 15:47 被阅读0次

    我不经常使用 React,所以每当我需要在 React 中做最小的事情时,我都必须查看文档、教程或在论坛上发布问题。

    这就是我决定做这个记忆辅助工具的原因,鉴于我的记忆力不是那么好,我想为什么不用我所知道的关于 React 的所有概念来制作一个可怕的记忆辅助工具。

    所以我可以不时阅读它,从而加强我对 React 的了解。

    如果您有想法或建议,请不要犹豫,并在评论部分这样做。

    备忘录

    创建一个 React 应用程序

    // 创建
    npx create-react-app my-app-name
    
    // 启动
    cd my-app-name
    yarn start
    
    // http://localhost:3000
    /**
    *第一个 React 功能组件
    *无需从 'react' 导入 React(自 React 17 起)
    *首字母必须大写
    *必须返回 JSX
    **/
    (src/App.js)
    // React component
    function App(){
      return <h1>Hello World</h1>
    } 
    
    export default App;
    

    这个组件如何渲染到浏览器?主项目文件是 src/index.js 并且在该文件中有渲染组件的指令

    ReactDOM.render(<App />, document.getElementById('root'))
    

    然后 App 组件将在 public/index.html 'root' div中呈现

    导入组件
    组件将在单独的文件中创建。每个组件都需要导出然后导入

    function Greeting(){
        return <h1>Hello World</h2>
    }
    export default Greeting
    

    然后可以导入该组件

    import Greeting from './Gretting'
    
    function App(){
        return <Greeting />
    }
    

    或名称导出...

    export function Greeting(){
        return <h1>Hello World</h2>
    }
    

    然后可以导入该组件

    import {Greeting} from './Gretting'
    //BEM 命名约定
    return (
    <div className="app">
      <h1 className="app_title">Welcome to my application: {appTitle}</h1>
      <div className="product">
        <h1 className="product__name--large">Product name: {product.name}</h1>
    <h1 className="product__name--small">Nick name: {product.nickName}</h1>
        <p className="product__description">Product description: {product.description}
      </div>
    <div>
    )
    

    JSX 规则
    返回单个元素(只有一个父元素)

    // not valid
    return <h1>Hello world</h1><h2>Hi!</h2>
    
    return (
        <>
            <h1>Hello World</h1>
            <h2>Hi!</h2>
        </>
    )
    

    使用 className 而不是 class
    所有属性名称都需要是驼峰式的

    // not valid
    return (
        <div class="title">
            Hello World
        </div>
    )
    
    // valid
    return (
        <div className="title">
        </div>
    )
    
    

    关闭每个元素

    return (
        <img src="http:example.com/image.jpg" />
        <input type="text" name="first_name" />
    )
    

    嵌套组件

    // Arrow function shorthand component
    const Person = () => <h1>Mike Taylor</h1>
    
    // Arrow function component
    const Message = () => {
        return <h1>Hello</h1>
    }
    
    // Function component
    function HelloWorld(){
      return (
          <>
              <Message />
              <Person />
          </>
      )
    } 
    

    组件 CSS

    (src/App.css)
    h1 {
        color: red;
    }
    
    (src/App.js)
    

    导入 CSS 文件

    import './App.css'
    
    function App(){
      return <h1>Hello World</h1>
    } 
    

    内联 CSS

    function App(){
      return <h1 style={{ color: 'red' }}>Hello World</h1>
    } 
    

    JSX 中的 JavaScript
    将 {} 括起来
    必须是表达式(返回值)

    function App(){
        const name = 'Mike'
        return (
          <>
              <h1>Hello {name}</h1>
              <p>{name === 'Mike' ? '(admin)': '(user)'}</p>
          </>
        )
    } 
    

    组件属性(道具)

    function App()
        return <Person name='Mike' age={29} />
    } 
    
    const Person = (props) => {
        return <h1>Name: {props.name}, Age: {props.age}</h1>
    }
    
    // or props object deconstructing
    const Person = ({name, age}) => {
        return <h1>Name: {name} Age: {age}</h1>
    }
    

    子组件道具(插槽)

    function App()
        return (
            <Person name='Mike' age={29}>
                Hi, this is a welcome message
            </Person>
        )
    } 
    
    const Person = (props) => {
        return (
            <h1>Name: {props.name}, Age: {props.age}</h1>
            <p>{props.children}</p>
        )
    }
    
    // or props object deconstructing
    const Person = ({name, age, children}) => {
        return (
            <h1>Name: {name} Age: {age}</h1>
            <p>{children}</p>
        )
    }
    

    默认道具值

    const Person = ({name, age, children}) => {
        return (
            <h1>Name: {name} Age: {age}</h1>
            <p>{children}</p>
        )
    }
    
    Person.defaultProps = {
        name: 'No name',
        age: 0,
    }
    

    列表

    const people = [
      {id: 1, name: 'Mike', age: 29},
      {id: 2, name: 'Peter', age: 24},
      {id: 3, name: 'John', age: 39},
    ]
    function App(){
        return (
            people.map(person => {
                return <Person name={person.name} age={person.age}/>
            })
        )
    } 
    
    const Person = (props) => {
      return (
          <h1>Name: {props.name}, Age: {props.age}</h1>
      )
    }
    

    带键的列表(用于 React 内部参考)

    function App(){
        return (
            people.map(person => {
                return <Person key={person.id} name={person.name} age={person.age}/>
            })
         )
    } 
    

    道具对象解构

    function App(){
      return people.map(person => <Person key={person.id} {...person} />)
    }
    
    const Person = (name, age) => {
      return (
          <h1>Name: {name}, Age: {age}</h1>
      )
    } 
    

    点击事件

    const clickHandler = () => alert('Hello World')
    function App(){
        return (
            <>
                <h1>Welcome to my app</h1>
                <button onClick={clickHandler}>Say Hi</button>
            </> 
        )
    } 
    

    或内联...

    function App(){
        return (
            <>
                <h1>Welcome to my app</h1>
                <button onClick={ () => alert('Hello World') }>Say Hi</button>
            </>
         )
    } 
    

    要传递参数,我们需要使用箭头函数

    const clickHandler = (message) => alert(message)
    function App(){
        return (
            <>
                <h1>Welcome to my app</h1>
                <button onClick={() => clickHandler('Hello World')}>Say Hi</button>
            </> 
        )
    } 
    

    e 用于事件参数

    const clickHandler = (e) => console.log(e.target)
    function App(){
        return (
            <>
                <h1>Welcome to my app</h1>
                <button onClick={() => clickHandler('Hello World')}>Say Hi</button>
            </> 
        )
    } 
    

    将事件从孩子传递给父母

    function Todo({item, onDelete}) {
        return (
          <div>
            {item}
            <button onClick={() => onDelete(item)} 
          </div>
        )
    }
    
    function Todos() {
      const handleDelete = (todo) => {
        const newTodos = todos.filter(item => item !== todo)
        setTodos(() => newTodos)
      }
    
      return (
        {todos.map(todo => (
           <Todo item={todo} onDelete={handleDelete}/>
        }
      )
    }
    

    使用状态钩子
    useState 的目的是处理反应式数据。应用程序中发生变化的任何数据都称为状态。当状态发生变化时,您需要做出反应来更新 UI。

    钩子总是以“use”前缀开头
    必须仅在 React 组件/函数中调用
    必须在功能组件的顶层调用
    不能有条件地调用声明
    useState 返回一个 2 的数组:[状态值,设置状态函数]

    import React, {useState} from 'react';
    
    const DisplayTitle = () => {
      const [title, setTitle] = useState('This is the Title')
      const handleClick = () => setTitle('New Title')
      return <>
        <h2>{title}</h2>
        <button type="button" className="btn" onClick={handleClick}>
          Change Title
        </button>
      </>
    };
    
    export default DisplayTitle;
    

    useState 与对象

    const DisplayTitle = () => {
      const [person, setPerson] = useState({name: 'Mike', age: 29})
      const handleClick = () => setPerson({...person, age: 35})
      return <>
        <h2>{title}</h2>
        <button type="button" className="btn" onClick={handleClick}>
          Change Age
        </button>
      </>
    };
    

    setState 函数形式

    function Counter() {
      const [count, setCount] = useState(0)
      // Use a function to set State
      const increase = () => setCount(() => count + 1)
      return (
        <>
          <h1>Counter</h1>
          <p>{count}</p>
          <button onClick={increase} className='btn'> + </button>
          <button onClick={() => setCount(() => count - 1)} className='btn'> - </button>
        </>
      )
    }
    

    使用效果
    在 React 中,您可能希望在生命周期事件或副作用之后执行代码。

    默认情况下,useEffect 函数在每次重新渲染后执行。然后您可以在每次组件更新时执行代码。

    import React, { useEffect } from 'react';
    
    function IncreaseValue() {
        const [value, setValue] = useState(0)
        useEffect(() => {
            document.title = `New value: ${value}` 
        })
        return <button onClick={() => setValue(value + 1)}>Increase</button>
    }
    条件使用效果
    条件需要放在 useEffect 函数中
    useEffect(() => {
        if (value > 0) {
            document.title = `New value: ${value}` 
        }
    })
    

    useEffect 依赖列表
    如果您只想在第一次渲染时或仅在特定状态更改时执行代码怎么办?您可以使用 useEffect 函数并将依赖项数组作为参数发送。

    仅当 state 在依赖项列表中时才会运行 useEffect。
    如果列表为空 [],则 useEffect 将仅在初始渲染时运行。

    useEffect(() => {
        document.title = `New value: ${value}` 
    }, [])
    // Noted the empty array. useEffect will then only run once on initial render
    
    useEffect(() => {
        document.title = `New value: ${value}` 
    }, [value])
    // Will run each time 'value' state change.
    

    useEffect 清理函数
    如果每次卸载组件时都想执行代码怎么办?

    要仅在卸载/销毁组件时执行代码,您需要向 useEffect 函数添加“return”语句。

    useEffect(() =>  { 
        const timer = window.setInterval(() => { 
            setCount(count => count + 1)
        }, 1000)
        return () => clearInterval(timer)
    }, [])
    

    代码“clearInterval(timer)”只会在组件从 UI 中移除(卸载)之前执行

    条件渲染

    function DisplayGreeting() {
        const [name, setName] = useState('Mike')
        if (name === 'Mike') {
            return <h1>Hello admin {name}</h1> 
        }
        return <h1>Hello user {name}</h1> 
    }
    

    内联 If-Else

      return (
        <div>
          The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
        </div>
      );
    }
    

    内联逻辑 && 运算符。
    仅当第一个表达式为真
    时才显示truthy = Not : 0、""、null、undefined 和 NaN

      function DisplayUserInfo({active}) {
        return (
          <div>
            { active && <h1>User is active</h1>}
          </div>
        );
    }
    

    多个内联 If

    <span className={count === 0 && 'text-gray-500' || count > 0 && 'text-green-500' || count < 0 && 'text-red-500'}>{count}</span>
    

    形式

    const UserForm = () => {
      const [userName, setUserName] = useState('')
      const handleSubmit = (e) => {
        e.preventDefault()
        console.log(userName)
      }
    return (
    <>
        <form onSubmit={handleSubmit}>
          <input 
              value={userName} 
              onChange={(e) => setUserName(e.target.value)} 
              type="text" id="userName" 
              name="userName"
          />
           <button type="submit">Submit</button>
        </form>
    </>
    )
    };
    
    export default UserForm;
    

    使用引用
    useRef 主要用于定位 DOM 元素。但它也可用于在每次渲染之间保持/保留可变值。useRef 不会触发重新渲染(如 useState)。

    const UseRefBasics = () => {
      const refContainer = useRef(null)
      const handleSubmit = (e) => {
        e.preventDefault()
        console.log(refContainer.current.value)
      }
    
      useEffect(() => {
        refContainer.current.focus()
      }, [])
    
      return (
        <div>
          <form className="form" onSubmit={handleSubmit}>
            <div>
              <input ref={refContainer} type="text" />
              <button type="submit">Submit</button>
            </div>
          </form>
        </div>
      )
    };
    

    结论
    这就是今天的内容。我们还有很多事情要做,如果你觉得,请点击关注我!

    相关文章

      网友评论

          本文标题:一文加强对React的记忆(2021 年 6 月更新),收藏再也

          本文链接:https://www.haomeiwen.com/subject/uwkoeltx.html