【问题标题】:How to pass optional elements to a component as a prop in reactjsreactjs中如何将可选元素作为prop传递给组件
【发布时间】:2016-02-11 22:34:36
【问题描述】:

我正在尝试找出正确的“反应”方式将作为元素的可选道具传递给容器组件,该组件的处理方式与该组件的子组件不同。

举个简单的例子,我有一个 Panel 组件,它渲染它的子组件,它还有一个可选的“title”道具(为了这个例子,它是一个元素而不是一个字符串),它被特别渲染(放在一个特殊的地方,在保持抽象的同时有特殊的行为。

一种选择是让一个组件从子项中拉出并专门渲染:

<Panel>
   <Title> some stuff</Title>
   <div> some other stuff</div>
</Panel>

但是,把孩子们拉出来分开处理似乎很奇怪。

这通常在反应中是如何处理的,我什至认为这是正确的方式

【问题讨论】:

    标签: javascript reactjs components


    【解决方案1】:

    你可以这样做

    render(){
        <div>
            {this.props.title ? this.props.title : null}
            {this.props.children}
        </div>
    }
    

    基本上,如果您将标题元素作为道具传递,然后将其创建为元素并渲染它。否则只需输入 null ...

    要创建它,你会做这样的事情。

    <Panel title={<Title>Something Here</Title>}
        <div> something here</div>
    </Panel>
    

    这通常是 react 处理可选子组件的方式

    【讨论】:

      【解决方案2】:

      你不需要做任何特别的事情。只需将 title 组件作为 prop 传递,然后在您希望渲染它的任何位置使用 {this.props.title}

      class Panel extends React.Component {
        render() {
          return <div>
            {this.props.title}
            <div>Some other stuff...</div>
          </div>;
        }
      }
      
      class App extends React.Component {
        render() {
          var title = <Title>My Title</Title>;
          return <Panel title={title}/>;
        }
      }
      

      如果您没有为 title 属性传递任何值(或者如果该值为 falsenullundefined),则不会在那里呈现任何内容。

      这是 React 中相当常见的模式。

      【讨论】:

      • 啊,谢谢。我坚持认为“title={title}”必须是原始类型。
      • 将标题 propType 限制为实际的标题组件是否是一种常见的反应模式(甚至可能)?
      • 一般情况下是正确的,但也有例外。如果道具包含不存在的数组,它会产生错误(这就是我在测试中得到的)。这 : {this.props.data.contactDetails [1]} 将产生错误if : this.props.data.contactDetails [1] 没有提供。
      【解决方案3】:

      当您需要来自可选 prop 的属性时,您必须首先检查 prop 是否已交付。否则,你会得到一个:

      TypeError: Cannot read property 'yourPropProperty' of undefined
      

      在条件渲染上下文中(取决于我的可选 this.props.ignore 数组),这不会工作:

      {!this.props.ignore.includes('div')) && (
         <div>
            Hey
         </div>
      )}
      

      相反,您应该这样做:

      {(!this.props.ignore || !this.props.ignore.includes('div'))) && (
         <div>
            Hey
         </div>
      )}
      

      【讨论】:

        【解决方案4】:

        您可以做的一件事是为您的组件设置默认道具(通常初始化为无操作)。

        例如,如果你想有一个可选的功能道具:

        class NewComponent extends React.Component {
            ...
            componentDidMount() {
                this.props.functionThatDoesSomething()
            }
        }
        
        NewComponent.defaultProps = {
            functionThatDoesSomething: () => {}
        }
        

        这样,父组件可以选择是否传递函数prop,你的应用不会因为错误而崩溃

        this.props.functionThatDoesSomething 不是函数 .

        【讨论】:

          猜你喜欢
          • 2020-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-21
          • 2022-11-13
          • 1970-01-01
          • 1970-01-01
          • 2021-11-02
          相关资源
          最近更新 更多