简体   繁体   中英

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)

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 . Put object to useState where properties of that object will be all names(Ids) of child-components

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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