【问题标题】:Unable to render children in React Component无法在 React 组件中渲染子级
【发布时间】:2023-03-20 08:28:01
【问题描述】:

我正在调用一个带有这样子的 React 组件:

<SignUpFormWizard
          initialValues={initialFormValues}
          onSubmit={(values, props) => this._submit(values, props)}
        >
    <Text style={styles.lightText}>Wizard.</Text>
</SignUpFormWizard>

而我的SignUpFormWizard 组件是这样的:

export default class SignUpFormWizard extends React.Component {
    // static Page = ({ children }) => children;

    constructor(props) {
        super(props);
        // console.log(props);
        this.state = { page: 0, values: props.initialValues };
    }

    render() {
        const { children } = this.props;
        console.log("Render");
        console.log(children);
        return <React.Fragment />;
    }
}

但是,每当我执行此操作时,系统都会冻结一段时间并以消息 There was a problem sending log messages to your development environment. 结束

当我尝试渲染 { children } 时,我收到一条错误消息,指出 Invariant Violation: Invariant Violation: Invariant Violation: Objects are not valid as a React child (found: object with keys {children}).

我需要知道如何去做。基本上,这只是我想要实现的框架代码,即在 React 组件中渲染子组件。

【问题讨论】:

  • 向我们展示您究竟是如何尝试渲染{this.props.children}
  • render() 方法中使用return { this.props.children }; 渲染它。

标签: javascript reactjs react-native expo


【解决方案1】:

如果您只想渲染 children 仅此而已,那么您可以更新 SignUpFormWizard 使其看起来像这样:

const SignUpFormWizard = ({ children }) => <>{children}</>;

export default SignUpFormWizard;

由于您调用 SignUpFormWizard 组件,例如:

<SignUpFormWizard
  initialValues={initialFormValues}
  onSubmit={(values, props) => this._submit(values, props)}
>
  <Text style={styles.lightText}>Wizard.</Text>
</SignUpFormWizard>

我猜你需要阅读 initialValuesonSubmit 类似的道具:

const SignUpFormWizard = ({ children, initialValues, onSubmit }) => 
  <>
    {initialValues.map(value => (<div>{value}</div>))}
    {children}
    <button onClick={onSubmit}>Sign Up</button>
  </>;

export default SignUpFormWizard;

【讨论】:

  • 我不得不使用一个类(状态要求等),但我发现了一个小错误。我已经接受了你的回答。感谢您的帮助?
  • @GauravWadhwani 好的,很酷!很高兴你解决了你的问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2017-05-21
  • 2020-10-15
相关资源
最近更新 更多