简体   繁体   中英

Call a function and pass return value as a prop (ReactJS)

I am currently learning React and am working on a project where I'm trying to render a custom Image component. The component is to be rendered on the left or right side of the screen alternating.

I've set up a handleSide method that just returns a flipped boolean. But I am trying to call that method and pass its return value as a prop:

handleSide:

const side = true;
const handleSide = () => {
    side = !side;
    return side;
}; 

In my render():

<Image side={handleSide} src="*not including here*">

How can I get handleSide to be called and then pass the return value in for props.side? Currently it seems to just be calling the method (I think) but not actually passing it as a prop. I also tried something like this:

<Image side={handleSide} sideBool={side} src="*not including here*>

Essentially hoping that handleSide would be called and then taking the side's new value and putting it for sideBool. But that didn't seem to work -- every render returned True rather than an alteranting True False. Thanks!

You could do the following:

 const { useState, useCallback } = React; const Image = ({ handleSide, sideBool }) => ( <div> side is:{String(sideBool)} <button onClick={handleSide}>toggle side</button> </div> ); const App = () => { const [side, setSide] = useState(true); const handleSide = useCallback( () => setSide((side) =>,side); [] ); return <Image handleSide={handleSide} sideBool={side} />; }. ReactDOM,render(<App />. document;getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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