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

问题描述

我在ReactJS中有两个功能组件,父级和子级。 我将功能作为道具从父组件传递给孩子。

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

孩子


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

在上述“组件子组件”中,控制台上的输出为“父”,换句话说,函数print_name被绑定(绑定)到“父组件”。 如何使函数不绑定到父组件,以便子组件中的print_name输出“子”。

此外,绑定在基于功能的组件中实际上如何工作?

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

解决方法

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

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

孩子:

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中,作为prop传递的函数用于修改子组件的父状态,让我们假设子组件是从父组件接收名称以进行编辑编辑的输入,因为在子组件中您无法更改prop或父状态直接。

另一个建议:

尝试在子组件中克隆通过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>)
}