javascript - 你如何在 React 中为嵌套形状提供默认 Prop ?

标签 javascript reactjs

React 中有没有一种方法可以为特定形状的嵌套项目数组提供默认 Prop ?

给出下面的示例,可以看到我的第一次尝试,但是这并没有按预期工作。

static propTypes = {
    heading: PT.string,
    items: PT.arrayOf(PT.shape({
        href: PT.string,
        label: PT.string,
    })).isRequired,
};

static defaultProps = {
    heading: 'this works',
    items: [{
        href: '/',
        label: ' - this does not - ',
    }],
};

在这个例子中,我期望如下:

// Given these props
const passedInProps = {
    items: [{ href: 'foo' }, { href: 'bar' }]
};

// Would resolve to:
const props = {
    heading: 'this works',
    items: [
      { href: 'foo', label: ' - this does not - ' },
      { href: 'bar', label: ' - this does not - ' },
    ]
};

最佳答案

没有。默认 Prop 只是浅合并。

但是,一种方法可能是为每个项目设置一个子组件。这样每个 Child 组件都会从 item 数组中接收一个对象,然后默认的 props 将按照您的预期合并。

例如:

var Parent = React.createClass({

  propTypes: {
    heading: React.PropTypes.string,
    items: React.PropTypes.arrayOf(React.PropTypes.shape({
      href: React.PropTypes.string,
      label: React.PropTypes.string,
    })).isRequired
  },

  getDefaultProps: function() {
    return {
      heading: 'this works',
      items: [{
        href: '/',
        label: ' - this does not - ',
      }],
    };
  },

  render: function() {
    return (
      <div>
        {this.props.item.map(function(item) {
          return <Child {...item} />
        })}
      </div>
    );
  }

});

var Child = React.createClass({

  propTypes: {
    href: React.PropTypes.string,
    label: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      href: '/',
      label: ' - this does not - '
    };
  },

  render: function() {
    return (
      <div />
        <p>href: {this.props.href}</p>
        <p>label: {this.props.label}
      </div>
    );
  }

});

关于javascript - 你如何在 React 中为嵌套形状提供默认 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123498/

相关文章:

reactjs - 来自来源 'http://localhost:3000'的邮件已被CORS政策: No 'Access-Control-Allow-Origin' header is present on the requested resource阻止

reactjs - 将 Sass (.scss) 添加到弹出的 create-react-app 配置中

reactjs - 世博会错误: Cannot read property 'statusBarHeight' of null

php - HTML 表单验证

javascript - 如何防止添加到主屏幕pwa在网站的www版本上再次提示?

javascript - 为什么 0 == ""在 JavaScript 中为真

javascript - 在多个元素上使用 jquery 插件并稍加修改

javascript - 制作一个js数组,输入框的值用空格分隔

reactjs - ThemedStyledProps 类型上不存在属性 'name'

javascript - 我无法在 React 上实现 Lightbox Gallery