【发布时间】:2020-07-08 08:01:11
【问题描述】:
我正在尝试转换class component to functional component。但收到此错误
函数组件不能有引用。你的意思是使用 React.forwardRef() 吗?
class component 的工作示例
https://codesandbox.io/s/highlight-search-results-wqtlm?file=/src/components/Search/List.js
现在我把list类组件改成函数组件
https://codesandbox.io/s/funny-bird-dkfpi?file=/src/components/List.js
我的代码中断并给出以下错误
函数组件不能有引用。你的意思是使用 React.forwardRef() 吗?
请建议如何解决此错误
import React, { useEffect, useRef, useState} from 'react';
import User from './User';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const List = ({users})=>{
const [focusedUser, setFocusedUser] = useState(-1);
const [scrollIntoView, setScrollIntoView] = useState(false);
const userRef = useRef();
const prev = usePrevious({focusedUser});
useEffect(()=>{
if (
focusedUser !== prev.focusedUser &&
scrollIntoView
) {
ensureFocusedItemVisible();
}
},[focusedUser])
const ensureFocusedItemVisible =()=> {
userRef.current &&
userRef.current.scrollIntoView({
behaviour: 'smooth',
block: 'center'
});
}
const handleKeyPress = e => {
// scroll into view only on keyboard navigation
setScrollIntoView( true );
// up arrow
if (e.keyCode === 38) {
const fu = focusedUser <= 0 ? 0 : focusedUser - 1;
setFocusedUser(fu);
}
// down arrow
if (e.keyCode === 40) {
const currentFocus = focusedUser;
// if down key is pressed multiple times on last list item, keep last item highlighted
const fu =
currentFocus >= users.length - 1
? users.length - 1
: currentFocus + 1;
setFocusedUser(fu);
}
};
const handleMouseEvent = id => {
userRef.current && userRef.current.focus();
setScrollIntoView(false);
setFocusedUser(parseInt(id))
};
const listElements = users.map((user, index) => {
const focused = index === focusedUser;
return (
<User
divId={index}
data={user}
focused={focused}
ref={focused && userRef}
handleKeyPress={handleKeyPress}
handleMouseEvent={handleMouseEvent}
/>
);
});
return <div className="result-list">{listElements}</div>;
}
export default List;
【问题讨论】:
标签: javascript reactjs react-hooks