请结合使用componentDidMount和componentDidupdate重写这段代码
我还有其他代码或需要添加到代码中的功能,并且作为基于类的组件,这不起作用。
但是基于功能的组件,我将能够在代码中引入更多功能。
谢谢。
var ps;
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
backgroundColor: "black",
activeColor: "info"
};
this.mainPanel = React.createRef();
}
componentDidMount() {
if (navigator.platform.indexOf("Win") > -1) {
ps = new PerfectScrollbar(this.mainPanel.current);
document.body.classList.toggle("perfect-scrollbar-on");
}
}
componentWillUnmount() {
if (navigator.platform.indexOf("Win") > -1) {
ps.destroy();
document.body.classList.toggle("perfect-scrollbar-on");
}
}
componentDidUpdate(e) {
if (e.history.action === "PUSH") {
this.mainPanel.current.scrollTop = 0;
document.scrollingElement.scrollTop = 0;
}
}
handleActiveClick = color => {
this.setState({ activeColor: color });
};
handleBgClick = color => {
this.setState({ backgroundColor: color });
};
我所做的无法更新的内容。
var ps;
const Dashboard = (props) => {
const[backgroundColor, setBackgroundColor] = useState("black");
const[activeColor, setActiveColor] = useState("info");
const [handleActiveClick, setHandleActiveClick] =useState({activeColor: 'color'});
const [handleBgClick, setHandleBgClick] =useState({backgroundColor: 'color'});
const mainPanel = useRef(null);
useEffect(()=>{
if (navigator.platform.indexOf("Win") > -1) {
ps = new PerfectScrollbar(mainPanel.current);
document.body.classList.toggle("perfect-scrollbar-on");
}
return () =>{
ps.destroy();
document.body.classList.toggle("perfect-scrollbar-on");
}
},[]);
useEffect((e)=>{
if (e.history.action === "PUSH") {
mainPanel.current.scrollTop = 0;
document.scrollingElement.scrollTop = 0;
}
},['history']);
答案 0 :(得分:0)
我试过这种方法
useEffect(() => {
if (navigator.platform.indexOf("Win") > -1) {
ps = new PerfectScrollbar(mainPanel.current);
document.body.classList.toggle("perfect-scrollbar-on");
}
return () => {
ps.destroy();
document.body.classList.toggle("perfect-scrollbar-on");
};
}, [actionPush(props)]);
function actionPush(props) {
if (props.history.action === "PUSH") {
console.log(mainPanel.current);
mainPanel.current.scrollTop = 0;
document.scrollingElement.scrollTop = 0;
}
}