I am trying to pass function as prop to child comp and then pass it as argument to function in the child component without any luck. I want to set the some value by calling the function setSomeValue(). inside the IncrementValue() function of child component.
const ParentComponent = () => {
function setSomeValue(val){
console.log('ur value: ' + val);
}
return (
<ChildComponent setSomeValue={setSomeValue} />
);
});
Child component Below:
const ChildComponent = (props) => {
function IncrementValue(setSomeValue){
setSomeValue(6);
}
function handleClick(){
IncrementValue(props.setSomeValue);
}
return (
<button onClick={() => handleClick()}
);
})
;
const ParentComponent = () => {
const [value, setValue] = React.useState(0);
React.useEffect(() => {
console.log('ur value: ' + value);
}, [value]);
function setSomeValue(){
setValue(value + 1);
}
return (
<ChildComponent value={value} setSomeValue={setSomeValue} />
);
});
const ChildComponent = ({value, setSomeValue}) => {
return (
<>
<p>Value is: {value}</p>
<button onClick={setSomeValue}>Increment</button>
</>
);
})
Your code seems to be working fine apart from small syntax errors. You may want to correct them as shown below and try re-running it again.
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
function setSomeValue(val){
console.log('ur value: ' + val);
}
return (
<ChildComponent setSomeValue={setSomeValue} />
);
};
and the ChildComponent code as:
import React from 'react';
const ChildComponent = (props) => {
function IncrementValue(setSomeValue){
setSomeValue(6);
}
function handleClick(){
IncrementValue(props.setSomeValue);
}
return (
<button onClick={() => handleClick()}/>
);
};
export default ChildComponent;
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.