【问题标题】:Attaching props on a stateless function from props从 props 将 props 附加到无状态函数上
【发布时间】:2016-11-11 23:42:59
【问题描述】:

我正在构建一个 React 组件,它通过 prop component={MyTemplate} 接收一个组件(PropTypes.funcPropTypes.element),它将用作模板,类似于 react-router 进行路由定义的方式。

在组件内部,我想将道具附加到 component 元素。根据文档,我知道我应该使用cloneElement 来附加道具。

class MyComponent extends Component {
  // ...

  render () {
    const {component, blockProps} = this.props;
    const body = cloneElement(component, blockProps);

    return (
      <div className="sortable-block__body">
        {body}
      </div>
    );
  }
}

// later when rendering the component
<MyComponent component={component} ... />

在渲染组件时 React 抛出 Invariant Violation:

未捕获的不变违规:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。

cloneElement 不将无状态函数视为ReactElement 吗? 如果没有,那么如何管理向无状态组件添加道具?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    element prop 类型需要一个元素,类似于 &lt;MyTemplate /&gt; — 即带有 props。但是您接受的是元素构造函数 (MyTemplate)。

    另外,要从构造函数创建实例,您不需要cloneElement,而是使用 JSX 语法(并将变量大写):

    const Component = this.props.component;
    const body = <Component {...blockProps} />
    

    【讨论】:

    • &lt;component {...blockProps}/&gt; 之前尝试过,但没有成功。但是,如果我将component 分配给一个名为Component 的变量,它就可以工作。感谢帮助,不知道首字母大写有这种效果。
    • 如果不大写,React 将其视为标签名称,而不是组件
    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 2018-09-13
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多