How could I call the function from a component to another component inside it? For example, when clicking the button on TestContentMain, I want to call the TestContent2's addOne immediately, but how and what is the best way to do it? Thanks
TestContentMain.js:
import React from 'react';
import TestContent2 from './TestContent2';
export default function TestContentMain() {
return (
<div>
<TestContent2 />
<button
onClick={() => {
alert('Want to call TestContent2->addOne immediately, but how?');
}}
>
Test button
</button>
</div>
);
}
TestContent2.js:
import React from 'react';
export default function TestContent2() {
const countRef = useRef(0);
const addOne = () => {
countRef.current++;
console.log(`Clicked ${countRef.current} times`);
};
console.log('I rendered!');
return <button onClick={addOne}>Click me</button>;
}