【问题标题】:Moving logic to child component from a parent将逻辑从父组件移至子组件
【发布时间】:2020-06-23 22:03:13
【问题描述】:

我的情况是,位于父组件中的函数为模态组件处理 onOK,我将其定位在父组件中的原因是由于单击 onOk 按钮后会调用另一个本地函数

我想将其移至子级,因为 Modal 应该负责 onOK 逻辑,我可以让两个组件保持可见状态或创建一个商店,但问题是如果涉及另一个功能并且该功能是如何处理它粘在父母身上

父母

  handleModalOk = () => {
            this.onRadioButtonChange(2)
            this.setState({visible: false,});
        };

孩子

<Modal
     title={t('preferenceConfirmTitle')}
     visible={this.props.visible}
     onOk={this.props.onOk}

谢谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以将位于父级的函数传递给子级。这是一个例子:

    // Parent.js
    import React, {useState} from "react";
    
    import Child from "./Child";
    
    const Parent = () => {
        const [myState, setMyState] = useState();
    
        const funcOnlyInParent = () => {
          console.log("I'm only in the parent");
        }
    
        const doSomething = (argsFromChild) => {
          setMyState(argsFromChild);
    
          funcOnlyInParent();
        }
      
       return (
           <div>
              <Child handleDoSomething={doStomething} />
           </div>
       )
    }
    
    // Child.js
    import React, {useState} from "react";
    
    const Child = (props) => {      
       return (
           <div>
              <button onClick={() => props.handleDoSomething("my arguments")}>Click</button>
           </div>
       )
    }
    

    Child 组件将触发父级中的doSomething 函数并传入它需要的任何参数。因为该函数是在Parent 组件中定义的,所以它还可以对只有父级才能访问的数据执行操作——比如设置父级的状态。

    【讨论】:

    • 谢谢你的努力,我不是想把它传给一个孩子,我希望孩子负责做某事=> 例如,父母向孩子抛出一个函数作为道具,那个函数只应在调用 dosomething 时调用
    • @ArtjomProzorov 让我看看我是否理解正确:1)子调用doSomething,2)调用父中的孤立函数?
    • 知道了 -> 和 -> handleModalOk = () => { this.props.onRadioChange(2); this.props.preferenceModalStore.setIsVisible(false) };
    • 是的,伙计,你说的有点不同,但你肯定让我走上了正确的轨道:)
    • @ArtjomProzorov 太棒了,很高兴听到这个消息。最好的问候
    【解决方案2】:
    const Parent = () => {
    
      const function1 = () => {
        // your local code 
      }
      
      return (
        <Modal parentFunction={function1} />
      )
    }
    
    const Modal = ({parentFunction}) => {   
      
      const onOK = () => {
        // your local code
        parentFunction()
      }   
       
      return (
        <button onClick={onOK}>Click</button>
       )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多