React只返回props.children

问题描述 投票:17回答:4

所有:

我对React很新,我想知道如何在不添加任何元素(仅用于处理某些数据)的情况下构建仅逻辑组件,例如:

class LogicCom extends Component {
    constructor(props){super(props);this.props = props;}
    render(){
        return (
            {this.props.children}
        )
    }
}
reactjs
4个回答
39
投票

编辑在React v16 +中,您可以从组件返回字符串和数组。因此,一个组件简单地返回它的孩子是完全有效的......

render() {
  return this.props.children
}

docs中了解更多相关信息。

原始答案

你有什么工作IFF只有一个孩子(你修复了你的语法错误)。但是,子节点可以是许多子节点的数组,并且您无法在render函数中返回数组。所以,你必须做两件事之一......

1)强制你的组件只接受一个React.Children的孩子......

class LogicCom extends Component {
    render(){
        // this will throw if there are many children
        return React.Children.only(this.props.children)
    }
}

2)将孩子包裹在另一个组件中......

class LogicCom extends Component {
    render(){
        return <div>{ this.props.children }</div>
    }
}

3
投票

React组件必须具有单个根DOM元素才能呈现。

来自the official docs

render()方法是必需的。

调用时,它应该检查this.props和this.state并返回一个子元素。此子元素可以是本机DOM组件的虚拟表示(例如或React.DOM.div()),也可以是您自己定义的其他复合组件。

您还可以返回null或false以指示您不希望呈现任何内容。在幕后,React呈现标签以使用我们当前的差异算法。返回null或false时,ReactDOM.findDOMNode(this)将返回null。

在你的情况下,它很容易 - 只需将你的this.props.children包裹在某种外部元素中。

render(){
    return (
        <div>{this.props.children}</div>
    )
}

2
投票

您只能在不包裹孩子的情况下返回孩子。 Trick是创建一个包装器组件,然后将子节点修改为一个数组,这是React所需要的。

Wrapper.js

import React, { Component } from 'react';

export default class extends Component {
  render() {
    return React.Children.toArray(this.props.children);
  }
}

现在你可以简单地在这个包装器组件中包装其他东西。

<Wrapper>
  <h1>Hello, world!</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed semper odio nec semper suscipit.</p>
</Wrapper>

现在包装器内的元素将呈现,而不必将其包装在DIV中。


1
投票

作为JCD stated,渲染必须返回单个根子或null。还有其他几个选择:

如果LogicCom不需要在树下传递数据,它可以用作叶子。

<Parent>
  <LogicCom />
  {/* other children */}
</Parent>

如果您确实需要传递数据(例如,LogicCom操纵其传入道具或生成新道具),您可以要求单个子项,如@Charlie's response中所述(propTypes进一步记录):

class LogicCom extends Component {
    render(){
        // this will throw if there are many children
        return React.Children.only(this.props.children)
    }
}

LogicCom.propTypes = {
    children: React.PropTypes.element
};

或者使用高阶组件构造来包装另一个组件:

const LogicCom = function (Wrapped) {
    return class extends Component {
      render () {
          // forward received props and override/add as needed
          <Wrapped {...this.props} />
      }
    }
};

// usage elsewhere: WrappedComponent will receive whatever props LogicCom
// receives + overrides/adds.
const WrappedComponent = LogicCom(AnotherComponent);
© www.soinside.com 2019 - 2024. All rights reserved.