From 2069b2cea5177e749e1d855f84b0551d238c19ee Mon Sep 17 00:00:00 2001 From: jaywcjlove Date: Tue, 4 Oct 2022 03:19:38 +0000 Subject: [PATCH] doc: update `react.md` cheatsheet. cdd57176b7d92531638718079d9d4cb9076c5737 --- docs/react.html | 82 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 66 insertions(+), 16 deletions(-) diff --git a/docs/react.html b/docs/react.html index dcd50bce..7fa6ac5f 100644 --- a/docs/react.html +++ b/docs/react.html @@ -251,7 +251,7 @@ </Fragment> ) -

从 @v16.2.0 开始,Fragment 可用于返回多个子节点,而无需向 DOM 添加额外的包装节点。

+

v16.2.0 开始 Fragment 可用于返回多个子节点,而无需向 DOM 添加额外的包装节点。或者使用 <></> 效果是一样的。

Portals

React 并没有创建一个新的 div。它只是把子元素渲染到 domNode 中。domNode 是一个可以在任何位置的有效 DOM 节点。

render() {
@@ -262,6 +262,56 @@
 }
 

提供了一种将子节点渲染到存在于父组件以外的 DOM 节点的优秀的方案

+

Refs 转发

+
const FancyButton = React.forwardRef(
+  (props, ref) => (
+    <button ref={ref} className="btn">
+      {props.children}
+    </button>
+  )
+);
+
+

使用

+
// 你可以直接获取 DOM button 的 ref:
+const ref = React.createRef();
+
+<FancyButton ref={ref}>
+  点击我
+</FancyButton>;
+
+

Class 组件内部使用 ref 属性

+
import { Component,createRef } from 'react';
+
+class MyComponent extends Component {
+  constructor(props) {
+    super(props);
+    this.myRef = createRef();
+  }
+
+  render() {
+    return <div ref={this.myRef} />;
+  }
+}
+
+

提示:Refs 适用于类组件,但不适用于函数组件(除非您使用 useRef hook,请参阅hooks

+

函数组件内部使用 ref 属性

+
function CustomTextInput(props) {
+  // 这里必须声明 $input,这样 ref 才可以引用它
+  const $input = useRef(null);
+  function handleClick() {
+    $input.current.focus();
+  }
+  return (
+    <div>
+      <input type="text" ref={$input} />
+      <input
+        type="button" value="聚焦文本输入"
+        onClick={handleClick}
+      />
+    </div>
+  );
+}
+

默认值

Class 组件默认 props

@@ -272,7 +322,7 @@ color: 'blue' }; -

使用

+

使用

<CustomButton /> ;
 

不传值 props.color 将自动设置为 blue

@@ -347,24 +397,24 @@ const root = ReactDOM.createRoot( document.getElementById('root') ); -const element = <h1>Hello, world</h1>; -root.render(element); + +const element = <h1>Hello, world</h1>; +root.render(element);

参考:渲染元素

JSX 属性

-
const element = (
-  <img src={user.avatarUrl} />
-);
-
-const element = (
-  <button className="btn">
-    点击我
-  </button>
-);
+
const avatarUrl = "img/picture.jpg"
+const element = <img src={avatarUrl} />;
+
+const element = (
+  <button className="btn">
+    点击我
+  </button>
+);
 

注意:类属性 className

JSX 表达式

-
let name = 'Josh Perez';
+
let name = '张三';
 let element = <h1>Hello, {name}</h1>;
 
 function fullName(firstName, lastName) {
@@ -372,7 +422,7 @@
 }
 let element = (
   <h1>
-    Hello, {fullName('Julie', 'Johnson')}
+    Hello, {fullName('三', '张')}
   </h1>
 );
 
@@ -439,7 +489,7 @@
}

注意:组件必须总是返回一些东西。

-

使用

+

使用

<Greeting firstName="" lastName="" />
 

JSX 三目运算符 / 与运算符 &&