React:内联有条件地将prop传递给组件 [英] React: inline conditionally pass prop to component

查看:331
本文介绍了React:内联有条件地将prop传递给组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法来有条件地传递道具而不是使用if语句。

I would like to know if there is a better way to conditionally pass a prop than using an if-statement.

例如,我现在有:

var parent = React.createClass({
  propTypes: {
    editable: React.PropTypes.bool.isRequired,
    editableOpts: React.PropTypes.shape({...})
  },
  render: function() {
    if(this.props.editable) {
      return (
        <Child editable={this.props.editableOpts} />
      );
    } else {
      // In this case, Child will use the editableOpts from its own getDefaultProps()
      return (
        <Child />
      );
    }
  }
});

有没有办法在没有if语句的情况下写这个?我正在考虑JSX中的一种内联if语句:

Is there a way to write this without the if-statement? I am was thinking something along the lines of a type of inline-if-statement in the JSX:

var parent = React.createClass({
  propTypes: {
    editable: React.PropTypes.bool.isRequired,
    editableOpts: React.PropTypes.shape({...})
  },
  render: function() {
    return (
      <Child 
        {this.props.editable ? editable={this.props.editableOpts} : null} 
      />
    );
  }
});

总结:我正试图找到一种方法为 Child 定义道具,但传递一个值(或做其他事情),使 Child 仍然拉出该道具的值来自孩子自己的 getDefaultProps()

To wrap-up: I'm trying to find a way to define a prop for Child, but pass a value (or do something else) such that Child still pulls that prop's value from Child's own getDefaultProps().

推荐答案

你很接近你的想法。事实证明,为支柱传递 undefined 与根本不包括它相同,这仍将触发默认支柱值。所以你可以这样做:

You were close with your idea. It turns out that passing undefined for a prop is the same as not including it at all, which will still trigger the default prop value. So you could do something like this:

var parent = React.createClass({
  propTypes: {
    editable: React.PropTypes.bool.isRequired,
    editableOpts: React.PropTypes.shape({...})
  },
  render: function() {
    return <Child 
      editable={this.props.editable ?
                  this.props.editableOpts : 
                  undefined}
    />;
  }
});

这篇关于React:内联有条件地将prop传递给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆