有没有办法将一个组件传递给另一个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'));

当前回答

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 />

我更喜欢使用React内置API:

import React, {cloneElement, Component} from "react";
import PropTypes from "prop-types";

export class Test extends Component {
  render() {
    const {children, wrapper} = this.props;
    return (
      cloneElement(wrapper, {
        ...wrapper.props,
        children
      })
    );
  }
}

Test.propTypes = {
  wrapper: PropTypes.element,
  // ... other props
};

Test.defaultProps = {
  wrapper: <div/>,
  // ... other props
};

然后你可以用你想要的东西替换包装器div:

<Test wrapper={<span className="LOL"/>}>
  <div>child1</div>
  <div>child2</div>
</Test> 

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

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

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

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

你可以将你的react组件传递给另一个组件,并从child发出函数

import CustomerFilters;

parent:

const handleFilterChange = (value) => {
 console.log(value)
}

<DataGrid
   contentName="customer"
   fetchFilterComponents = {<CustomerFilters onSelectFilter={handleFilterChange} />}
</DataGrid>


child:
CustomerFilters
return (

        <select className="filters-dropdown" onChange={onSelectFilter}>
          <option>Select Filter</option>
          {customerFilterOptions?.map((filter: any) => {
            return <option value={filter.value}>{filter.name}</option>;
          })}
        </select>
)