首页 > 解决方案 > 在 Parent 中传递两个函数

问题描述

我在将两个函数从子级传递给父级时遇到问题。子函数是 => 

setValueLocally = () => {...}
show_User_Poll = () => {...}

在 Parent 中,我通过创建另外两个函数来访问这些函数。


savePollData() { this.refs.savePoll.setValueLocally()  }

_show_User_Poll() { this.refs.showPoll.show_User_Poll() }

我正在父级中呈现这些功能。问题是如何为上述两个功能设置参考?

 <Child ref = {"savePoll", "showPoll"} />

我正在这样做,但它给出了错误..

对于单一功能,它对我有用

 <Child ref="savePoll"/> 

标签: react-native

解决方案


您应该在子组件上创建一个引用,然后您可以从 Parent 访问子组件的所有方法。PS:您只能引用类组件,因此您的 Child 需要是一个类。

const Parent = props => {
  const childRef = React.useRef(null);

  const savePollData = () => {
    childRef.current.savePollData();
  };

  const _show_User_Poll = () => {
    childRef.current.show_User_Poll();
  };

  return <Child ref={childRef} />;
};

class Child extends React.Component {
  setValueLocally = () => {
    return null;
  };

  show_User_Poll = () => {
    return null;
  };
  render() {
    return null;
  }
}

推荐阅读