简体   繁体   中英

React controlling state with an outside component

React newbie here, I have a component for login which has two states (logged and not), and a button, a button click makes a form appear for the user.

function Main() {

    const [state, setState] = useState(false);
    function buttonClick(event) {
        state = !state;
    }

    return (
    <div id='main'>
        <p id='main-body'>{lorem}</p>
        { state ? <LoginForm /> : <LoginButton />}
    </div>
 )
}

my issue is that the onClick itself (and the button) are in another component:

function LoginButton() {
    return (
        <div class="btn-centered">
            <button type="button" class="btn btn-outline-primary btn-lg btn-centered" onClick={}>Login</button>
        </div>
    )
}

Have I understood the concept wrongly? How do I achieve the result I want with the outside component? Thanks a lot for any help, I'd VERY appreciate explanations so I can learn.

You can pass buttonClick method in login button component like this

<LoginButton onClick={buttonClick} />

and inside Loginbutton component you can do something like this

<button type="button" ... onClick={props.onClick}>Login</button>

so when you click login button it will trigger you buttonClick method.

the LoginButton should get props and return a callback to the Main that will switch the state and you should also use useState to change the state in order to change the DOM,

thats how it should look

function Main() {

const [state, setState] = useState(false);
function buttonClick(event) {
    setState((prev) => !prev);
}

return (
    <div id='main'>
        <p id='main-body'>{lorem}</p>
        { state ? <LoginForm  /> : <LoginButton callback={buttonClick} />}
    </div>
)

function LoginButton(props) {
    const {callback} = props;
return (
    <div class="btn-centered">
        <button type="button" class="btn btn-outline-primary btn-lg btn-centered" onClick={callback}>Login</button>
    </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