所以我决定将我的React Class组件重写为React Hook组件,并且在我的Class组件中我这样做了
<canvas ref='canvas'></canvas>这种方法不再起作用了。那么我应该如何使用refs呢?在文档中只说ref仍然在工作。
谢谢!
发布于 2019-01-16 01:36:15
对于钩子,您可以使用useRef钩子。
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}看看这里的useRef文档:https://reactjs.org/docs/hooks-reference.html#useref
发布于 2019-07-19 04:15:43
如果你想在map函数中使用ref:
export default () => {
const items = ['apple', 'orange', 'mango'];
// 1) create an array of refs
const itemRefs = useRef(items.map(() => React.createRef()));
useEffect(() => {
// 3) access a ref, for example 0
itemRefs.current[0].current.focus()
}, []);
return (
<ul>
{items.map((item, i) => (
// 2) attach ref to each item
<li key={item} ref={itemRefs.current[i]}>{item}</li>
))}
</ul>
);
};发布于 2020-04-08 06:52:44
在React Native中以非冗长的方式展示了它是如何为我工作的一个例子。
export function Screen() {
/*
* Call function for example of access to the component,
* being able to access calls to its functions.
*/
const callRef = () => {
testeRef.example();
};
return (
<CustomComponent ref={(e) => testRef = e}></CustomComponent>
);
}https://stackoverflow.com/questions/53678308
复制相似问题