react(二) useAPI

39 阅读1分钟
  ### Ref

1. 一般用于指向某个具体元素,相当于全局变量,

  • 类组件
this.inputRef = createRef(null);
this.eleRef = createRef(null);

handleClick = () => { 
  this.inputRef.current.focus(); //点击事件 使input框聚焦
  
  this.eleRef.current.innerHTML = `${ this.inputRef.current.value }` //获取到input 中的值 并展示
}

<div ref={this.eleRef}></div>
<input ref={this.inputRef} />
  • 函数组件
this.inputRef = useRef(null);

2. ref转发 - 父组件调用子组件方法

如:页面展示弹窗,页面和弹窗内部都能控制显/隐;

// 父级组件
export default class RefInput extends Component{
    constructor(props){
      super(props);
      this.exposeRef = createRef(null);
    }
    render(){
        return(
           <div>
        <FancyInput ref={this.exposeRef}/>
        <button onClick={()=>{this.exposeRef.current.focus()}}>focus</button>
        <button onClick={()=>{this.exposeRef.current.changeVal(Math.random())}}>change</button>
        </div> 
        );
        
    }
};
// 子组件
const MyInput = (props, ref) => {
   const inputRef = useRef();
   const focus = () => { inputRef.current.focus(); }
   const changeVal = (val) => {inputRef.current.value = val;}

   useImperativeHandle(ref, ()=> ({ //父级可调用的函数
      focus, changeVal
   }))
   return <div>
     <input ref={inputRef}/>
   </div>
}
// 子组件需转发
const FancyInput = forwardRef(MyInput);

Context

避免props层层传递;provider,consumer不会自动更新组件

const NavContext = createContext(null);
const history = window.history;

export default function FunContext() {
    return (
        <NavContext.Provider value={history}> //提供数据
            <Parent />
        </NavContext.Provider>
    )
}
function Parent() {
    return (
        <div>
            <TestChild />
        </div>
    )
}
const TestChild = () => {
    const history = useContext(NavContext); / 使用数据
    return <button onClick={() => { history.pushState({}, undefined, 'test') }}>test</button>
}

高阶组件

1. 属性代理

  • 增加属性

上面的子组件,如果有多个的话,那么每个都需要定义

const history = useContext(NavContext); 才能使用

属性代理可以代替传入

const WithRouter = (Component) => {
    return function WithRouterComponent(){
       const history = useContext(NavContext);
       return <Component value={history} />
    }
}

const WithRouterChild = WithRouter(TestChild);
  • 装饰/组件增强
export default function PropsProperty() {
    return (
        <div><HocProperty name={'外层传递的属性值'} /> </div>
    )
}
--- 原始组件
const PRoperty = (props) => {
    return <div>普普通通的组件 - {props.name}</div>
}
--- 高阶组件
const Decorator = (Component) => {
    return (props) => { -----外层传递的属性值
        return <div>
            ---------------  // 增加了展示样式
            <Component {...props} />
            ---------------
        </div>
    }
}
const HocProperty = Decorator(PRoperty);

2.反向继承

参考 juejin.cn/post/730601…