【问题标题】:Passing props to dynamic react component将道具传递给动态反应组件
【发布时间】:2019-01-27 01:12:08
【问题描述】:

所以我有下面的代码来加载一个名为 foo 的自定义组件。组件的加载工作正常,但 props 并没有像我希望的那样传递给它

Container component

....
const id= foo
React.createElement(LoadComponent(id, attributes))
...

Custom component

export const LoadComponent = (id, attributes) => {
    /*This will load up foo.js*/
    const Component = require(`./${id}`);

    return Component;
};

在这种情况下,如何将属性 prop 传递给组件?我不断收到渲染异常。

【问题讨论】:

    标签: reactjs dynamic components


    【解决方案1】:

    这是一个简化的演示:https://codesandbox.io/s/zrw7x1zrrp

    props 正在作为createElement 的第二个参数传递给组件

    const id = "foo";
    const LoadComponent = props => {
      return props.id;
    };
    
    ReactDOM.render(
      React.createElement(LoadComponent, { id }, null),
      document.getElementById("root")
    );
    

    React.createElement(component, props, ...children)

    https://reactjs.org/docs/react-without-jsx.html

    【讨论】:

      【解决方案2】:

      您正在尝试做的事情有点令人困惑。如果您使用 JSX,则不需要调用 React.createElement

      如果你坚持不使用 JSX,React.createElement 可以按照React's API 采用 3 个参数。因此,在您的情况下,您的代码将是 React.createElement(LoadComponent, { id, attributes }, null),其中第三个参数是孩子。

      现在,可以从自定义组件的 props 对象中访问 idattributes。所以你有两个选择:

      1. Destructureprops 对象:

        export const LoadComponent = ({ id, attributes }) => {
            /*This will load up foo.js*/
            const Component = require(`./${id}`);
        
            return Component;
        };
        
      2. 直接使用 props 对象:

        export const LoadComponent = (props) => {
            /*This will load up foo.js*/
            const Component = require(`./${props.id}`);
        
            return Component;
        };
        

      【讨论】:

        猜你喜欢
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 2018-07-17
        • 2020-03-26
        • 2021-09-27
        • 1970-01-01
        相关资源
        最近更新 更多