简体   繁体   English

为嵌套组件导出 React 中的钩子?

[英]export Hooks in React for Nested Components?

I'm exporting hooks with nested components so that the parent can toggle state of a child.我正在导出带有嵌套组件的钩子,以便父级可以切换子级的状态。 How can I make this toggle work with hooks instead of classic classes or old school functions?我怎样才能让这个切换与钩子一起工作,而不是经典的类或老式的函数?

Child Component子组件

export let visible;
export let setVisible = () => {};

export const ToggleSwitch = () => {
    const [visible, setVisibile] = useState(false);
    return visible && (
       <MyComponent />
    )
}

Parent家长

import * as ToggleSwitch from "ToggleSwitch";

export const Parent: React.FC<props> = (props) => {
    return (
       <div>
          <button onClick={() => ToggleSwitch.setVisible(true)} />
       </div>
    )
}

Error: Linter says [setVisible] is unused variable in the child... (but required in the parent)错误:Linter 说 [setVisible] 在子级中是未使用的变量......(但在父级中是必需的)

You can move visible state to parent like this:您可以像这样将可见状态移动到父级:

const Child = ({ visible }) => {
    return visible && <h2>Child</h2>;
};

const Parent = () => {
  const [visible, setVisible] = React.useState(false);
  return (
    <div>
        <h1>Parent</h1>
        <Child visible={visible} />
        <button onClick={() => setVisible(visible => !visible)}>
            Toggle
        </button>
    </div>
  );
};

If you have many child-components you should make more complex logic in setVisible .如果你有很多子组件,你应该在setVisible创建更复杂的逻辑。 Put object to useState where properties of that object will be all names(Ids) of child-components将对象置于 useState 中,其中该对象的属性将是子组件的所有名称(Id)

如您所知,React 是单向数据绑定,因此如果您想传递任何道具或状态,您只有一种方法可以将其从父组件传递到子组件,并且如果逻辑变得更大,则必须将其设置为全局状态通过使用状态管理库或上下文 API 与反应钩子使用 reducer 和使用效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM