首页 文章

我可以在ReactJS中转换原始元素的子元素吗?

提问于
浏览
5

如果我有以下HTML:

<div id="myreactcomponent">
  <h1>Headline</h1>
  <p>Content</p>
</div>

我将一个ReactJS组件初始化为#myreactcomponent div,我可以以某种方式呈现组件内的h1和p元素吗?像这样的东西:

return (
  <Header></Header>
  { place h1 and p here }
  <Footer></Footer>
);

在ReactJS中有选择吗?

You can check this JSFiddle to see a demonstration of my problem.

对于熟悉 Angular 的人:我在React中搜索transclude选项和AngularJS指令的 <ng-transclude/> 标记 .

对于熟悉 Polymer 的人:我在React中搜索等效的 <content/> 标签 .

UPDATE

我尝试了 this.props.children 属性,但据我所知,这仅在初始HTML已经在React组件中时才有效 . 我真的需要渲染我最初渲染第一个React组件的元素的子元素 .

UPDATE 2

将HTML移动到组件的初始化中(如update of the JSFiddle所示)在我的情况下不是一个选项,因为不同的系统会渲染初始HTML和React组件 .

3 回答

  • 2

    像这样......

    ..
    render(){
    return (
    <Header></Header>
    <span dangerouslySetInnerHTML={{__html:'content'}}></span>
    <Footer></Footer>
    )
    }
    ..
    var content = '<h1>This is a header</h1><p>This is some para..</p>'
    

    这是你所指的......你可以阅读更多关于这个here .

  • 3

    是的,要做到这一点,请使用 this.props.children .

    例如,如果你有一个像这样使用的React组件:

    <MyReactComponent>
      <h1>Headline</h1>
      <p>Content</p>
    </MyReactComponent>
    

    您可以在 render MyReactComponent 中执行此操作来传输子元素 h1p

    return (
      <Header></Header>
      { this.props.children }
      <Footer></Footer>
    );
    
  • 2

    是的,这是可能的 .

    在反应类中你有 this.props.children

    所以在父组件中:

    function render() {
      return <MyComponent><div class="my-child">My text</div></MyComponent>;
    }
    

    然后在子组件中

    function render() {
      return <div class="child-wrapper">{this.props.children}</div>;
    }
    

    https://facebook.github.io/react/tips/children-props-type.html

相关问题