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

当前回答

下面是一个父List react组件的例子,whos props包含一个react元素。在这种情况下,只传递了一个Link react组件(如dom渲染中所示)。

class Link extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    return (
      <div>
        <p>{this.props.name}</p>
      </div>
     );
  }
}
class List extends React.Component {
  render(){
   return(
    <div>
       {this.props.element}
       {this.props.element}
    </div>
   );
  }
}

ReactDOM.render(
  <List element = {<Link name = "working"/>}/>,
  document.getElementById('root')
);

其他回答

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

你可以把它作为普通的道具传递:foo={<ComponentOne />}

例如:

const ComponentOne = () => <div>Hello world!</div>
const ComponentTwo = () => (
  <div>
    <div>Hola el mundo!</div>
    <ComponentThree foo={<ComponentOne />} />
  </div>
)
const ComponentThree = ({ foo }) => <div>{foo}</div>

实际上,您的问题是如何编写高阶组件(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>
    );
}

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

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

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

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

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

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