Javascript 在React中更新全局变量/状态

Javascript 在React中更新全局变量/状态,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,还是很新的反应,一直在做一个项目。我一直需要将此计数器作为全局变量进行跟踪,并在组件中更新其值。我已经使用setState hook const[currentMaxRow,setRow]=useState(3)声明了这个计数器,我想在它被传递到的组件中更新这个值。我不知道该怎么做,谢谢 这实际上非常简单。您唯一需要做的就是将“setRow”函数传递给您的子组件。现在,只要您想更新父组件中的状态,您基本上可以在子组件中调用函数prop function App() { const [cur

还是很新的反应,一直在做一个项目。我一直需要将此计数器作为全局变量进行跟踪,并在组件中更新其值。我已经使用setState hook const[currentMaxRow,setRow]=useState(3)声明了这个计数器,我想在它被传递到的组件中更新这个值。我不知道该怎么做,谢谢

这实际上非常简单。您唯一需要做的就是将“setRow”函数传递给您的子组件。现在,只要您想更新父组件中的状态,您基本上可以在子组件中调用函数prop

 function App() {
  const [currentMaxRow, setRow] = React.useState(3)  

  const incrementVal = () => {
    setRow(currentMaxRow + 1);
  };
  return (
    <div>
      <p>You clicked {currentMaxRow} times</p>
      <Child count={currentMaxRow} incrementVal={incrementVal} />
    </div>
  );
}
const Child = props => (
  <>
    <button onClick={props.incrementVal}>Click me</button>
    <h3>{props.count}</h3>
  </>
);

但是,我认为值得一提的是,组件的状态和全局变量不是一回事。我强烈建议您阅读有关组件、状态和道具的React文档。这会让事情变得更清楚

使用钩子的示例应用程序

-将值和函数传递给子组件

 function App() {
  const [currentMaxRow, setRow] = React.useState(3)  

  const incrementVal = () => {
    setRow(currentMaxRow + 1);
  };
  return (
    <div>
      <p>You clicked {currentMaxRow} times</p>
      <Child count={currentMaxRow} incrementVal={incrementVal} />
    </div>
  );
}
const Child = props => (
  <>
    <button onClick={props.incrementVal}>Click me</button>
    <h3>{props.count}</h3>
  </>
);
函数应用程序(){
常量[currentMaxRow,setRow]=React.useState(3)
常量增量=()=>{
setRow(currentMaxRow+1);
};
返回(
您单击了{currentMaxRow}次

); } const Child=props=>( 点击我 {props.count} );
检查此项,希望有帮助