无法在React Component中渲染子级

时间:2019-04-13 10:02:16

标签: javascript reactjs react-native expo

我正在像这样调用带有孩子的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组件中呈现子组件。

1 个答案:

答案 0 :(得分:0)

如果仅想渲染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;