https://github.com/shunyue1320/mini-react
迷你版本 react 用于学习
https://github.com/shunyue1320/mini-react
Last synced: 7 months ago
JSON representation
迷你版本 react 用于学习
- Host: GitHub
- URL: https://github.com/shunyue1320/mini-react
- Owner: shunyue1320
- Created: 2021-12-14T01:28:20.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-06-02T01:54:29.000Z (over 3 years ago)
- Last Synced: 2025-01-30T09:24:12.647Z (9 months ago)
- Language: JavaScript
- Size: 771 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# mini-react
迷你版本 react 用于学习
## forwardRef
forwardRef将ref从父组件中转发到子组件中的dom元素上,子组件接受props和ref作为参数
## useImperativeHandle
useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值```js
function Child(props, ref) {
const inputRef = React.useRef();
React.useImperativeHandle(ref, () => ({
focus() {
inputRef.current.focus();
},
}));
return ;
}
const ForwardChild = React.forwardRef(Child); // forwardRef 作用就是给 Child 传递 ref 参数function Parent() {
let [number, setNumber] = React.useState(0);
const inputRef = React.useRef();
function getFocus() {
console.log(inputRef.current);
inputRef.current.focus();
}
return (
获得焦点
{number}
{
setNumber(number + 1);
}}
>
+
);
}
ReactDOM.render(, document.getElementById("root"));
```