将函数作为 prop 传递,然后使用函数组件将其作为参数传递给 ReactJs 中的函数

时间:2021-01-05 18:40:58

标签: javascript reactjs ecmascript-6

我试图将函数作为道具传递给子组件,然后将其作为参数传递给子组件中的函数,但没有任何运气。我想通过调用函数 setSomeValue() 来设置某个值。在子组件的 IncrementValue() 函数中。

const ParentComponent = () => {

function setSomeValue(val){
    console.log('ur value: ' + val);
}
  return (
    <ChildComponent setSomeValue={setSomeValue} />
);
});

下面的子组件:

const ChildComponent = (props) => {
 function IncrementValue(setSomeValue){
    setSomeValue(6);
 }

function handleClick(){
    IncrementValue(props.setSomeValue);
}
return (
    <button onClick={() => handleClick()}
);
})

;

2 个答案:

答案 0 :(得分:0)

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>
        </>
    );
})

答案 1 :(得分:0)

除了小的语法错误外,您的代码似乎运行良好。您可能需要按如下所示更正它们,然后再次尝试重新运行。

import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {

  function setSomeValue(val){
      console.log('ur value: ' + val);
  }
  return (
    <ChildComponent setSomeValue={setSomeValue} />
  );
};

和 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;