【问题标题】:React functional propsReact 函数式道具
【发布时间】:2017-11-14 12:30:13
【问题描述】:

我先给你举个例子:

<List hidden={this.state.hideList} />

对于这种情况,我希望 hidden prop 以下列方式运行:如果值为 true - 隐藏组件或显示其他内容。而List 不应该知道这个道具。

我对 React 的内部结构了解不多,但这似乎是可能的。我们只需要扩展React.Component 类。也许使用所有功能性道具进行全球扩展并不是一个好主意,但是在顶部有这样的东西会很好:

import { ReactComponent } from 'react'
import extend, { hidden } from 'react-functional-props'
const Component = extend(ReactComponent, hidden)

它让我想起了 Angular.js 中的指令,但在这里我们可以将它们组合起来。

【问题讨论】:

  • !this.state.hideList &amp;&amp; &lt;List /&gt;?
  • 更像是 angular 和 vue 中的指令,但 React 并没有刻意避免这种陷阱以支持条件渲染。?
  • 您可以创建这样一种机制,该机制将挂钩 un React.Component 构造函数或状态范例,并且一旦特定属性(例如隐藏)更改为以通用方式做出反应。一个装饰器,或者一个 muxin,如果你喜欢的话。

标签: javascript reactjs inheritance mixins


【解决方案1】:

你可以只在 render 方法中返回nullundefined 来阻止它渲染,或者使用条件类来隐藏它,像这样:

return !this.state.hideList && <List />;

关于

反应功能道具

在 React 中,你可以使用高阶组件(HOC)来实现你所需要的,例如:

const Hideable = Component => (props) => {
  const { isHidden, ...otherProps } = props;

  return !isHidden && (<Component {...otherProps} />);
};

const HideableList = Hideable(List);

...

return (
  <div>
    <HideableList isHidden={this.state.hideList} /> // The isHidden props is handled by the HOC
  </div>
);

但是对于这样一个简单的用例,我认为只处理父组件中的隐藏和显示会更加清晰。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2020-07-04
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多