gpt4 book ai didi

reactjs - 是否有一个函数返回一个 promise ,当在 React Native 中应用了对组件的任何未决更改时,该 promise 得到解决?

转载 作者:行者123 更新时间:2023-12-04 07:47:55 25 4
gpt4 key购买 nike

我想显示一个自定义输入组件,然后在单击按钮时调用它的方法:

const Parent = () => {
const customInputRef = useRef(null);

const [customInputVisible, setCustomInputVisible] = useState(false);

async function onPress() {
setCustomInputVisible(true);

await resolvePendingChanged(); // customInput is not null and can be accessed

customInputRef.current.customMethod();
}

return (
<View>
<Button onPress={onPress}>Press me!</Button>

{customInputVisible && <CustomInput ref={customInputRef} />}
</View>
);
}

我看到人们使用 custom forceUpdate function为了触发组件更新,但这对我来说并没有真正的帮助。
Svelte有这个 "tick" lifecycle hook这正是我需要的。

It returns a promise that resolves as soon as any pending statechanges have been applied to the DOM (or immediately, if there are nopending state changes).


是否有相当于 Svelte 的 tick在 React 中,如果不是,我如何在 React 中解决这个问题?

最佳答案

您可以创建一个使用 callback ref 的自定义 Hook 。设置实际的引用,并解决一个 promise :

const { forwardRef, useImperativeHandle, useRef, useState, useCallback, useMemo } = React;

const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();

useImperativeHandle(ref, () => ({
customMethod: () => {
inputRef.current.focus();
}
}), []);

return <input ref={inputRef} />;
});

class Deferred {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}

const waitForComponent = () => {
const componentRef = useRef(null);

return useMemo(() => {
let deferred = new Deferred();

return {
waitLoad(ref) {
componentRef.current = ref;

if (ref) deferred.resolve();
else deferred = new Deferred(); // create new Promise when ref is null
},
isLoaded: () => deferred.promise,
componentRef
};
}, []);
}

const Parent = () => {
const { waitLoad, componentRef, isLoaded } = waitForComponent();
const [customInputVisible, setCustomInputVisible] = useState(false);

function onPress() {
setCustomInputVisible(visible => !visible);

// use async here - SO snippet doesn't support async await
isLoaded().then(() => componentRef.current.customMethod());
}

return (
<div>
<button onClick={onPress}>Press me!</button>

{customInputVisible && <CustomInput ref={waitLoad} />}
</div>
);
};

ReactDOM.render(
<Parent />,
root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

关于reactjs - 是否有一个函数返回一个 promise ,当在 React Native 中应用了对组件的任何未决更改时,该 promise 得到解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67125455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com