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

当前回答

Facebook建议使用无状态组件 来源:https://web.archive.org/web/20160608001717/http: / / facebook.github.io / / docs / reusable-components.html反应

在理想的情况下,大多数组件都是无状态的 函数,因为在未来我们还会研究性能 特定于这些组件的优化,避免不必要的 检查和内存分配。这是推荐的模式 可能的。

function Label(props){
    return <span>{props.label}</span>;
}

function Hello(props){
    return <div>{props.label}{props.name}</div>;
}

var hello = Hello({name:"Joe", label:Label({label:"I am "})});

ReactDOM.render(hello,mountNode);

其他回答

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

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

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

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

虽然有点晚了,但这里有一个强大的HOC模式,可以通过将组件作为道具来覆盖组件。它简单而优雅。

假设MyComponent呈现了一个虚构的a组件,但您希望允许自定义重写a,在本例中为B,它将a包装在<div>…</div>,并将“!”附加到文本道具:

import A from 'fictional-tooltip';

const MyComponent = props => (
  <props.A text="World">Hello</props.A>
);
MyComponent.defaultProps = { A };

const B = props => (
  <div><A {...props} text={props.text + '!'}></div>
);

ReactDOM.render(<MyComponent A={B}/>);

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

你可以使用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} />