【问题标题】:React: How to dynamically append child components of differing types into a parent component?React:如何将不同类型的子组件动态附加到父组件中?
【发布时间】:2017-05-21 20:47:19
【问题描述】:

我正在尝试通过根据传递给<ParentComponent/> 的道具值附加各种子组件<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 list reactjs dynamic components


    【解决方案1】:

    只需编写一些 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 允许你做的事情:)

    【讨论】:

    • 谢谢,你是最棒的!
    【解决方案2】:

    我会回答我理解的问题,我不确定是你真正的问题,但它就是这样。

    首先将您的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} />;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      相关资源
      最近更新 更多