[英]Pass function as prop and then pass it as argument to function in ReactJs using functional component
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.我试图将 function 作为道具传递给子组件,然后将其作为参数传递给子组件中的 function,但没有任何运气。 I want to set the some value by calling the function setSomeValue().
我想通过调用 function setSomeValue() 来设置一些值。 inside the IncrementValue() function of child component.
在子组件的 IncrementValue() function 内。
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:和 ChildComponent 代码为:
import React from 'react';
const ChildComponent = (props) => {
function IncrementValue(setSomeValue){
setSomeValue(6);
}
function handleClick(){
IncrementValue(props.setSomeValue);
}
return (
<button onClick={() => handleClick()}/>
);
};
export default ChildComponent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.