[英]React | Call a function outside a component
I want to call the increment function of the CounterText
from the CounterButton
.我想从 CounterButton 调用
CounterText
的增量CounterButton
。
Note: This is not the particular case I'm trying to solve, but it's very similar.注意:这不是我要解决的特殊情况,但它非常相似。 I have a stipulation: I can't change the order of the items, they have to stay at one level, they have to be separate.
我有一个规定:我不能改变物品的顺序,它们必须保持在一个层次,它们必须分开。
I have one root component looks like this:我有一个根组件如下所示:
function App() {
return (
<div>
<CounterText/>
<CounterButton/>
</div>
);
}
CounterText looks like this: CounterText 看起来像这样:
const count = useRef(0);
function CounterText() {
function Increment() {
count.current++;
}
return(
<h2>{count.current}</h2>
);
}
CounterButton looks like this:计数器按钮如下所示:
function CounterButton() {
return (
<button>Increment</button>
);
}
PS.: Sorry for my English. PS.:对不起我的英语。
The usual solution is to lift state up into the parent component, and pass it down to child components as props or context , along with a function they can use to update the state if needed, something like this:通常的解决方案是将 state 提升到父组件中,并将其作为 props 或context传递给子组件,以及 function 他们可以用来更新 Z9ED39E2EA931586B6A985A6942EF7 之类的东西,如果需要,
function App() {
const [counter, setCounter] = useState(0);
const increment = useCallback(
() => setCounter(c => c + 1),
[]
);
return (
<div>
<CounterText counter={counter} />
<CounterButton increment={increment} />
</div>
);
}
function CounterText({counter}) {
return(
<h2>{counter}</h2>
);
}
function CounterButton({increment}) {
return (
<button onClick={increment}>Increment</button>
);
}
Live Example:现场示例:
const {useState, useCallback} = React; function App() { const [counter, setCounter] = useState(0); const increment = useCallback( () => setCounter(c => c + 1), [] ); return ( <div> <CounterText counter={counter} /> <CounterButton increment={increment} /> </div> ); } function CounterText({counter}) { return( <h2>{counter}</h2> ); } function CounterButton({increment}) { return ( <button onClick={increment}>Increment</button> ); } ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div> <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>
TheuseCallback
call there isn't required , but it makes the increment
function stable, which prevents unnecessarily re-rendering CounterButton
when counter
changes.那里的
useCallback
调用不是必需的,但它使increment
function 稳定,从而防止在counter
更改时不必要地重新渲染CounterButton
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.