Javascript 如何在ReactJS中的ComponentDidMount内部使用{useState} const[bgColor,setBgColor]=useState('black'); 类加速计扩展组件{ 建造师(道具){ 超级(道具); } componentDidMount=()=>{ $(窗口).on('scroll touchmove',函数(){ if($(document).scrollTop()>=$('.about-us').position().top){ 蓝色(“红色”); } }); }; render(){ 返回( ); } } 导出默认加速计;

Javascript 如何在ReactJS中的ComponentDidMount内部使用{useState} const[bgColor,setBgColor]=useState('black'); 类加速计扩展组件{ 建造师(道具){ 超级(道具); } componentDidMount=()=>{ $(窗口).on('scroll touchmove',函数(){ if($(document).scrollTop()>=$('.about-us').position().top){ 蓝色(“红色”); } }); }; render(){ 返回( ); } } 导出默认加速计;,javascript,jquery,reactjs,web,Javascript,Jquery,Reactjs,Web,这给了我一个错误,我们不能在开始时使用react钩子,但是,如果我在render中声明它们,它将不会被ComponentDidMount函数ReactJS识别React钩子只能用于功能组件,而ComponentDidMount是基于类的组件的生命周期方法。您可以在功能组件内部使用钩子,例如useState在类组件的生命周期中设置状态。你不想把两者混在一起。典型用法如下所示: const [bgColor, setBgColor] = useState('black'); class Accele

这给了我一个错误,我们不能在开始时使用react钩子,但是,如果我在render中声明它们,它将不会被ComponentDidMount函数ReactJS识别React钩子只能用于功能组件,而
ComponentDidMount
是基于类的组件的生命周期方法。

您可以在功能组件内部使用钩子,例如
useState
在类组件的生命周期中设置状态
。你不想把两者混在一起。典型用法如下所示:

const [bgColor, setBgColor] = useState('black');
class Accelerons extends Component {
constructor(props) {
super(props);
}
componentDidMount = () => {
$(window).on('scroll touchmove', function () {
  if ($(document).scrollTop() >= $('.about-us').position().top) {
    setBgColor('red');
  }
  
 });
 };
render() {
return (
  <article
    style={{
      backgroundColor: bgColor,
    }}
  >
    <Overlay />
    <Landing landing={DataAccelerons.landing} />
    <AboutUs itemColor={itemColor} accelerons={DataAccelerons} />
    <Participation itemColor={itemColor} accelerons={DataAccelerons} />
    <TeamMembers itemColor={itemColor} accelerons={DataAccelerons} />
    <Results itemColor={itemColor} accelerons={DataAccelerons} />
    <Footer
      accentColor={DataAccelerons.accentColor}
      footerColors={DataAccelerons.footerColors}
    />
  </article>
);
}
}
export default Accelerons;
import React,{useState}来自“React”;
函数示例(){
const[myVal,setMyVal]=useState(“你好世界”);
返回(
{myVal}

); }


如果您想使用生命周期方法(如<代码>组件DealStuts),可以考虑使用。另外,您不能在

render
方法内部使用
setState
,因为它会触发无限调用。

您只能在函数组件内部使用钩子,在类组件中需要使用
this.setState
import React, { useState } from 'react';

function Example() {
  const [myVal, setMyVal] = useState('Hello World');

  return (
    <div>
      <p>{myVal}</p>
    </div>
  );
}