【问题标题】:react is it possible to fire function implemnted on one child from another child?反应是否可以从另一个孩子触发一个孩子实施的功能?
【发布时间】:2020-07-04 08:26:32
【问题描述】:

我有 3 个组件:

  1. 父母
  2. 孩子1
  3. Child2 - 不是一个真正的 React 组件(它是一个使用第三个 JavaScript 库的组件,它直接操作 DOM 并且不由 React 管理。 此组件永远不会仅在 componentDidMount 和 componentWillReceiveProps 上呈现和变异)

我希望在 Child2 上从 Child1 触发函数(让我们称她为“triggerCallback”)。 triggerCallback 的实现必须在 Child2 上,因为它会改变 Child2 的 vars(我不想由 Parent 的状态管理的变量!)。

import React, { Component } from "react";

const Child1 = props => {
  return <button onClick={props.triggerCallback}>Click Me</button>;
};

class Child2 extends Component {
  data = [];

  shouldComponentUpdate() {
    return false;
  }

  componentWillReceiveProps(receviedProps) {
      // here I need to add a prop or a callback notification to fire 'triggerCallback', how?
  }

  triggerCallback = action => {
    console.log("i triggerd from Child1!");
    // here mutate data!
  };

  // componentDidMount() {} and some extra methods.....

  render() {
    return null;
  }
}
const Parent = props => {
  // how do i pass function implemnted on Child2 to be called from Child1?
  return (
    <div>
      <Child1 />
      <Child2 />
    </div>
  );
};


提前致谢!

【问题讨论】:

  • 所以将回调从父级传递给子级。当点击孩子时,父母设置一个状态,该状态值被传递给另一个孩子。在另一个孩子获取更新的道具值时,您可以触发方法调用。

标签: javascript reactjs


【解决方案1】:

您应该查看render props。请注意,我无法尝试我的示例,因此请将其视为一种伪代码

import React, { Component } from "react";

const Child1 = props => {
  return <button onClick={props.triggerCallback}>Click Me</button>;
};

class Child2 extends Component {
  data = [];

  shouldComponentUpdate() {
    return false;
  }

  constructor(props) {
      // Feed the function in the setter revieved as props
      super(props);
      props.getCallBack(this.triggerCallback);
  }

  triggerCallback = action => {
    console.log("i triggerd from Child1!");
    // here mutate data!
  };

  // componentDidMount() {} and some extra methods.....

  render() {
    return null;
  }
}
const Parent = props => {
  // Use a state that contains child2's function or an empty callback
  const [func, setFunc] = React.useState(() => void(0));
  // send setter as props to child2
  return (
    <div>
      <Child1 triggerCallback={func} />
      <Child2 getCallBack={(cb) => {setFunc(cb);}} />
    </div>
  );

【讨论】:

  • 哇,这是个好主意!但显然这不可能从另一个组件更改一个组件的功能:“警告:无法从不同组件的功能体内更新组件。”我认为以这种方式实现我想要的东西是不可能的,需要用另一种方法来实现
  • @EliavLouski 也许我认为问题出在渲染期间调用了 useState,您可以尝试执行 let func = () => void(0);然后在 getCallBack={(cb) => {func = cb;}} 或者你可以使用React Context
猜你喜欢
  • 2018-12-16
  • 2013-04-22
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
相关资源
最近更新 更多