我目前正在学习React Hooks功能,所以我创建了一个小实验,如果单击该按钮,将出现一个不可见(未安装)的框;如果该框可见,并且您单击页面上除该框以外的任何位置,则该框将消失。我正在努力使盒子消失,而且我不知道是什么引起了该错误。
初始状态和减速器:
const initialState = { visible: false };
const reducer = (state, action) => {
switch (action.type) {
case 'show':
return { visible: true };
case 'hide':
return { visible: false };
default:
return state;
}
};
Box组件:
function Box() {
const [state, dispatch] = useReducer(reducer, initialState);
const boxElement = useRef(null);
const boxStyle = {
width: '200px',
height: '200px',
background: 'blue'
};
function hideBox(e) {
if(!boxElement.current.contains(e.target)) {
dispatch({ type: 'hide' });
}
}
useEffect(() => {
window.addEventListener('click', hideBox);
return () => {
window.removeEventListener('click', hideBox);
}
});
return <div style={boxStyle} ref={boxElement} />
}
主要:
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box /> }
<button onClick={showBox}>Show box</button>
</section>
)
}
答案 0 :(得分:1)
您正在使用两个useReducer实例,而您只需要在App component
级别拥有一个实例并传递dispatch as a prop to Box
,否则您将只更新Box中useReducer所使用的状态,而不会App组件中的状态
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box dispatch={dispatch}/> }
<button onClick={showBox}>Show box</button>
</section>
)
}
Box.js
function Box({dispatch}) {
const boxElement = useRef(null);
const boxStyle = {
width: '200px',
height: '200px',
background: 'blue'
};
function hideBox(e) {
if(!boxElement.current.contains(e.target)) {
dispatch({ type: 'hide' });
}
}
useEffect(() => {
window.addEventListener('click', hideBox);
return () => {
window.removeEventListener('click', hideBox);
}
});
return <div style={boxStyle} ref={boxElement} />
}