[英]how to export a hook local variable from another file along with the component in react?
i want to use the Aya varriable in app.js (the code below is in a component) but i can't export it as it's local to the function我想在 app.js 中使用 Aya 变量(下面的代码在一个组件中)但我无法导出它,因为它是函数的本地变量
function BasicExample() {
const [Aya, setAya] = useState({data});
// code containing modifications to apply to Aya
}
export default BasicExample
Lift state up . 状态提升。 Basically define the state in App and pass a handler that does the update to the state down to your child component so it can call it with a new value.基本上在 App 中定义状态,并将对状态进行更新的处理程序传递给您的子组件,以便它可以使用新值调用它。
In this example I have the main component which renders a child component.在此示例中,我有呈现子组件的主要组件。 In that component is a div that displays the count
from the parent state, and a button to increment its value.在该组件中有一个显示父状态count
的 div 和一个用于递增其值的按钮。 Note that a function (the handler) is written in the parent component, and then a reference to it is passed down into the props of the child component - along with the value.请注意,一个函数(处理程序)写在父组件中,然后对它的引用连同值一起传递到子组件的 props 中。
When the button is clicked the function is called.当按钮被点击时,函数被调用。 This updates the state which causes a new render, and the updated state is reflected in the child component by the updated value.这会更新导致新渲染的状态,并且更新后的状态会通过更新后的值反映在子组件中。
const { Fragment, useState } = React; function Example() { // Initialise state const [ count, setCount ] = useState(0); // A function called `handleClick` that // updates the state. This handler is passed down // to the child component via its props function handleClick() { setCount(prev => prev + 1); } // The child component accepts both the // `count` state, and the handler as its props return ( <ChildComponent count={count} handleClick={handleClick} /> ); } // We destructure the count and the (reference to the) // function from the component's props. // When the button is clicked it calls the handler. // Changes to the state are reflected here when the parent // component re-renders function ChildComponent({ count, handleClick }) { return ( <Fragment> <div>{count}</div> <button type="button" onClick={handleClick} >Increment count </button> </Fragment> ); } ReactDOM.render( <Example />, document.getElementById('react') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.