繁体   English   中英

React:如何动态地将不同类型的子组件附加到父组件中?

[英]React: How to dynamically append child components of differing types into a parent component?

我试图根据传递给<ParentComponent/>的props值附加各种子组件<ChildComponen1/>, <ChildComponen3/>, <ChildComponen3/>来动态设置组件<ParentComponent/>的内容。 父组件是一个列表,子组件是具有不同内容(css,html)的列表项

下面,我详细介绍了一种我认为适合这种情况的方法,但是,如果您有另一种(更有效的)方法来实现使用各种不同的子组件动态填充父组件的指定目标,则将不胜感激。 谢谢

class ParentComponent extends React.Component{
    render(){
       return(

            <ComponentSwitch type="ChildComponen1"/>  
            <ComponentSwitch type="ChildComponen2"/>
      )
    }
}


class ComponentSwitch extends React.Component{
    render(){
          return(
            //How would I most effectively create a switch here?
          )
    }
}

...child components omitted for brevity

实现此功能的最有效方式是什么? 谢谢

只是写一些Javascript ...
例如,这里有很多可能性:

class ComponentSwitch extends React.Component {
  renderA() {
    return (
      <div>
        ... lot of child components here
      </div>
    );
  }

  render() {
    if (this.props.a) {
      return this.renderA();
    }

    return <B />;
  }
}

或使用switch语句并返回组件进行渲染。 不管你做什么

class ComponentSwitch extends React.Component {
  render() {
    switch (this.props.component) {
      case 'a':
        return <A />;

      case 'b':
        return <B />;

      default:
        return <C />;
    }
  }
}

做任何JS允许您做的事情:)

我将回答我所理解的问题,我不确定您的真正问题是什么,但是这确实可以解决。

首先,将您的type参数设置为您希望其表示的真实Class

import ChildComponent1 from './ChildComponent1.jsx';
import ChildComponent2 from './ChildComponent2.jsx';

class ParentComponent extends React.Component{
  render(){
     return(
        <ComponentSwitch type={ChildComponen1} name='John'/>  
        <ComponentSwitch type={ChildComponen2} name='Doe'/>
      )
  }
}

然后从props提取type ,并将其余的props传递给子Component

class ComponentSwitch extends React.Component{
    render(){
      const {
        type: Component,
        ...props,
      } = this.props;

      // props will now have 'name' and other props ready for the child component
      return <Component {...props} />;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM