如何避免 ReactJS 中功能组件的自动绑定

How to avoid auto binding in functional components in ReactJS

我在 ReactJS 中有两个功能组件,Parent 和 Child。 我将函数作为道具从 parent 组件传递给 child。

    const export function Parent() {
      const name = "parent";
      function print_name() {
        console.log(name);
      }
      return (
        <Child print_name={print_name} />
      )
    };

child


    const export function Child(props) {
      const name = "child";
      props.print_name(); //logs parent
      return (<p>Child</p>)
    }

在上面的组件Child中,控制台的输出是“parent”或者换句话说,函数print_name被绑定(绑定)到Parent成分。 如何使函数不绑定到 parent 组件,以便 Child 组件中的 print_name 输出“child”。

此外,绑定在 functional-based 组件中实际上是如何工作的?

我不想在 Child 组件中创建一个单独的函数,以便我可以重用 Parent 组件中的代码。

该函数在其定义的上下文中执行,因此它引用在其定义之前声明的 name 并记录它,以使其打印您必须的 child 名称将该名称作为参数传递:

const export function Parent() {
  const name = "parent";
  function print_name(_name=name) {//by default takes the parent name
    console.log(_name);
  }
  return (
    <Child print_name={print_name} />
  )
};

child :

const export function Child(props) {
  const name = "child";
  props.print_name(name); //logs child
 props.print_name(); //without parameter it logs parent
  return (<p>Child</p>)
}

在 React.js 中,作为 props 传递的函数用于修改 child 组件的 parent 状态,我们假设 child 组件是一个接收名称的输入从 parent 到编辑编辑因为在 child 组件中你不能直接改变道具或 parent 状态。

另一个建议:

尝试克隆通过 child 组件中的 props 传递的函数,例如:

const export function Child(props) {
  const name = "child";

Function.prototype.clone = function() {
  return new Function('return ' + this.toString())();
};


const print_child=props.print_name.clone();

   print_child();//expected to log child

  return (<p>Child</p>)
}