是否有可能在一个孩子身上启用另一个孩子的点火功能?

问题描述 投票:0回答:1

我有3个组成部分:

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

我希望在Child2上从Child1触发功能(让我们称其为'triggerCallback')。triggerCallback的实现必须在Child2上实现,因为它会突变Child2的变量(我不想由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个回答
0
投票
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> );
© www.soinside.com 2019 - 2024. All rights reserved.