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 添加额外的包装节点。或者使用 <></>
效果是一样的。
React 并没有创建一个新的 div
。它只是把子元素渲染到 domNode
中。domNode
是一个可以在任何位置的有效 DOM 节点。
render() {
@@ -262,6 +262,56 @@
}
提供了一种将子节点渲染到存在于父组件以外的 DOM 节点的优秀的方案
+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>;
+
+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)
+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>
+ );
+}
+
<CustomButton /> ;
不传值 props.color
将自动设置为 blue
参考:渲染元素
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
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="张" />