简体   繁体   English

在 React 中更新全局变量 / State

[英]Updating Global Variable / State in React

Still quite new to React and have been working on a project.对 React 还是很陌生,并且一直在做一个项目。 I've been needing to keep track of this counter as a global variable and update its value inside a component.我一直需要将此计数器作为全局变量进行跟踪,并在组件内更新其值。 I've declared this counter using the setState hook const [currentMaxRow, setRow] = useState(3) and I want to update this value inside the component it's being passed into.我已经使用 setState hook const [currentMaxRow, setRow] = useState(3) 声明了这个计数器,我想在它被传递到的组件中更新这个值。 Not really sure how to go about this, thanks!不太清楚如何 go 关于这个,谢谢!

This is actually quite straightforward.这实际上非常简单。 The only thing you need to do is to also pass the "setRow" function to your child component.您唯一需要做的就是将“setRow”function 也传递给您的子组件。 Now anytime you want to update the state in the parent, you basically call the function prop inside your child component.现在,只要您想在父组件中更新 state,您基本上可以在子组件中调用 function 属性。

However, I think it's worth mentioning that a component's state and a global variable are not the same thing.但是,我认为值得一提的是,组件的 state 和全局变量不是一回事。 I highly recommend you read the React documentation regarding components, state and props.我强烈建议您阅读有关组件、state 和道具的 React 文档。 It'll clear things up a whole lot more!它会让事情变得更清楚!

Sample application using hooks使用钩子的示例应用程序

-passing value and function to child component. - 将值和 function 传递给子组件。

 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>
  </>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM