简体   繁体   English

在具useState Hook的功能组件中与子代反应Render道具

[英]React Render prop with Children in a functional component with useState Hook

I am using a Create-React-App through Codesandbox using hook capable versions. 我正在使用支持钩子的版本通过Codesandbox使用Create-React-App。 I am trying to create a simple toggle using newer React options of Stateless functional components, and hooks. 我正在尝试使用无状态功能组件和挂钩的较新React选项创建一个简单的切换。 I created a renderprop pattern using children prop, but am getting a "children is not a function error". 我使用children prop创建了renderprop模式,但出现“ children不是函数错误”。 Professor Google has failed me. Google教授让我失败了。

App.js App.js

import React from "react";
import ReactDOM from "react-dom";
import Toggle from "./Toggle";
import "./styles.css";

const App = () => {
  return (
    <div className="App">
      <Toggle>
        <Toggle>
          {({ show, toggleShow }) => (
            <div>
              {show && <h1>Show Me</h1>}
              <button onClick={toggleShow}>Show / Hide</button>
            </div>
          )}
        </Toggle>
      </Toggle>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

and Toggle.js 和Toggle.js

import { useState } from "react";

const Toggle = ({ children }) => {
  let [show, setShow] = useState(false);

  const toggleShow = () => setShow((show = !show));

  return children({ show, toggleShow });
};

export default Toggle;

CodeSandbox CodeSandbox

<Toggle>
   <Toggle>

The outer Toggle has as its children another Toggle component, so this is where the exception is being thrown. 外部Toggle具有另一个Toggle组件作为其children ,因此将在此处引发异常。 The inner Toggle would be fine since its children is indeed a function, but the exception prevents the rendering from getting there. 内部的Toggle很好,因为它的children确实是一个函数,但是异常阻止了渲染到达那里。

I'm not quite sure what your goal is nesting Toggles inside toggles, so perhaps the fix is to just delete one of them. 我不太确定您的目标是在切换器中嵌套切换,因此解决方法是仅删除其中之一。 Alternatively, if your intention is to allow non-functions as children, then you can modify your Toggle component to something like this: 另外,如果您打算允许非功能作为子代,则可以将Toggle组件修改为以下形式:

const Toggle = ({ children }) => {
  let [show, setShow] = useState(false);

  const toggleShow = () => setShow((show = !show));

  if (typeof children === 'function') {
    return children({ show, toggleShow });
  }
  return children;
};

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

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