react hooks之useRef

在函数组件中的一个全局变量,不会因为重复 render 重复申明

const SaveVal = () => {
    let timer = setTimeout(() => {});
    let ref = useRef(timer);
    let [count, setCount] = useState(0)
    return (
        <div>
            {timer}~{ref.current}~{count}<br />
            <button onClick={() => setCount(x => x+1)}></button>
        </div>
    );
}

作用于Dom元素

const SaveEle = () => {
    let ref = useRef<HTMLInputElement>(null);
    let [val, setVal] = useState(0);
    return (
        <div>
            <div>{val}</div>
            <input ref={ref}/> <br />
            <button onClick={() => setVal(() => Number(ref.current!.value))}>get Value</button>
        </div>
    );
}

获取子组件的实例(只有类组件可用)

class Instance extends React.Component {
    state = {
        count: 0
    }
    public render() {
        return (
            <div>
                {this.state.count}<button onClick={() => {this.setState({count: this.state.count + 1})}}></button>
            </div>
        );
    }
}
const Cls = () => {
    let ref = useRef<Instance>(null);
    return (
        <>
            <Instance ref={ref}></Instance>
            {ref.current != null&&ref.current!.state.count}
        </>
    );
}

ref的值发生变化不会引起render

你可能感兴趣的:(reactjs,useRef)