我从React文档中获得的钩子不需要大型代码进行重构,并且很容易包含在现有代码中。我想从React组件渲染方法中调用可重复使用的下拉列表。这是我的代码:
//navigation.js
import {DropdownToggler} from './dropdown.js';
export class ErrorTriangle extends Component {
render(){
return(
{DropdownToggler({uiElement: {
toggler: <img src={MyImg}/>,
field: <div className={'errorMessage'}>
<p>Dropdown content</p>
</div >
}})
}
)
}
}
//dropdown.js
import React, {useEffect, useRef, useState} from "react";
import {store} from "../api/redux/store";
const DropdownToggler = (props) => {
const myRef = useRef(null);
const [showField, setShow] = useState(false);
const isMobile = store.getState().isMobile;
const remove = (e) => {
e.stopPropagation();
if (myRef && myRef.current.contains(e.target)) {
return
}
setShow(false);
if (isMobile===true) {
document.removeEventListener('touchend', remove, false)
} else {
document.removeEventListener('mouseup', remove, false)
}
};
const show = (e) => {
e.stopPropagation();
if (showField) {
return
}
setShow(true);
if (isMobile===true) {
document.addEventListener('touchend', remove, false)
} else {
document.addEventListener('mouseup', remove, false)
}
};
return (
<>
{React.cloneElement(props.uiElement.toggler, {
onTouchEnd: (e) => show(e),
onMouseUp: isMobile ? null : (e) => show(e)
})}
{showField ? React.cloneElement(props.uiElement.field, {ref: node => myRef.current= node}) : null}
</>
)
};
export {DropdownToggler};
并获取错误:钩子只能在功能组件的主体内部调用。我已经检查了有关此问题的现有信息:
- React-Hot-Loader版本是4.8.0
- 我的React和React-Dom是同一版本16.8.4;
我的babel-config包含:
'use strict'; module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: ["@babel/plugin-proposal-class-properties", "jsx-control-statements", "react-hot-loader/babel"], };
也许问题是我正在打破钩子的规则https://reactjs.org/warnings/invalid-hook-call-warning.html。将欣赏详细的解释(示例)或想法为什么不起作用。
更改
export class ErrorTriangle extends Component {
render(){
return(
{DropdownToggler({uiElement: {
toggler: <img src={MyImg}/>,
field: <div className={'errorMessage'}>
<p>Dropdown content</p>
</div >
}})
}
)
}
}
to
export function ErrorTriangle (props) {
return(
{DropdownToggler({uiElement: {
toggler: <img src={MyImg}/>,
field: <div className={'errorMessage'}>
<p>Dropdown content</p>
</div >
}})
}
)
}
或
更改
{DropdownToggler({uiElement: {
toggler: <img src={MyImg}/>,
field: <div className={'errorMessage'}>
<p>Dropdown content</p>
</div >
}})
}
to
{<DropdownToggler uiElement={{
toggler: <img src={MyImg}/>,
field: <div className={'errorMessage'}>
<p>Dropdown content</p>
</div >
}}/>
}
说明
要简单地说,如果您使用的是类,则应像此<Component />
一样调用组件函数,而不是正常函数Component()
,或者可以从使用类更改为使用组件函数