有没有办法将一个组件传递给另一个react组件?我想创建一个模型react组件,并传入另一个react组件,以透光该内容。

编辑:这里是一个reactJS代码,说明了我正在尝试做什么。http://codepen.io/aallbrig/pen/bEhjo

HTML

<div id="my-component">
    <p>Hi!</p>
</div>

反应

/**@jsx React.DOM*/

var BasicTransclusion = React.createClass({
  render: function() {
    // Below 'Added title' should be the child content of <p>Hi!</p>
    return (
      <div>
        <p> Added title </p>
        {this.props.children}
      </div>
    )
  }
});

React.renderComponent(BasicTransclusion(), document.getElementById('my-component'));

当前回答

你可以使用this.props.children来呈现组件包含的任何子元素:

const Wrap = ({ children }) => <div>{children}</div>

export default () => <Wrap><h1>Hello word</h1></Wrap>

其他回答

const ParentComponent = (props) => {
  return(
    {props.childComponent}
    //...additional JSX...
  )
}

//import component
import MyComponent from //...where ever

//place in var
const myComponent = <MyComponent />

//pass as prop
<ParentComponent childComponent={myComponent} />

你可以通过传入一个组件。道具和渲染它与插值。

var DivWrapper = React.createClass({
    render: function() {
        return <div>{ this.props.child }</div>;
    }
});

然后你将传入一个名为child的道具,它将是一个React组件。

您可以将组件作为道具传递,并使用与使用组件相同的方式。

function General(props) {
    ...
    return (<props.substitute a={A} b={B} />);
}

function SpecificA(props) { ... }
function SpecificB(props) { ... }

<General substitute=SpecificA />
<General substitute=SpecificB />

让我们创建一个包装器组件:

export const Wrapper = (props) => {
    return(<>
        <Menu />
        {props.children}
        <Footer />
        </>
    )
}

现在可以将新结构包含到现有结构中。 你需要将组件包含在一个路由中,例如:

 <Route path="/"  element={<Wrapper><ExampleComponent /></Wrapper>} />

实际上,您的问题是如何编写高阶组件(HOC)。使用HOC的主要目标是防止复制粘贴。你可以把你的HOC写成一个纯功能组件或一个类,这里有一个例子:

class Child extends Component {
    render() {
        return (
            <div>
                Child
            </div>
        );
    }
}

如果你想把你的父组件写成一个基于类的组件:

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

如果你想把你的父组件写成一个函数组件:

const Parent = props => {
    return (
        <div>
            {props.children}
        </div>
    );
}