简体   繁体   中英

How to pass value from child component(function based component )to parent component(class based component)

I need to pass the value from the child component to the parent component The child component is function based component and parent component is class based

child component

export const Checkbox = (props) =>{
const [checked,setChecked] = useState(false);
return (
        <Checkbox
            label={"XYZ"}
            value={checked}
            onChange={() => setChecked((checked) =>!checked)}
            />
);
}

Parent Component(classbased component)

render(){
  return(
   <Checkbox checked={this.props.value}>//not sure if i can get value like this
)
}

I want to get the boolean value of the check box if it is checked or unchecked

Handle your state and function in the parent component and pass the function as a prop to child component and try to invoke the function call within child component on onChange to lift your state up to parent.

I am in hurry and just adding an idea how can you achieve this in code.

const Parent = () => {

const [checked,setChecked] = useState(false);

    const changeYourState = (newState) => {
       // change your state here
    }

    return (
        <Child
            value={checked}
            initialState={checked}
            stateHandler={changeYourState}
            />
);
}

const Child = ({ stateHandler, initialState}) => {
   //you can manipulate your initial state based on your use case 

    return (
        <div >
            onChange={() => stateHandler(initialState)}
        </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