【问题标题】:"Don't set props of the React component" warning“不要设置 React 组件的 props”警告
【发布时间】:2015-09-21 10:34:56
【问题描述】:

我收到了这个 React.js 错误,我很想知道如何修复它。有没有办法在this 上拨打React.cloneElement

警告:不要设置 React 组件的 .props.children 。相反,在最初创建元素时指定正确的值或使用 React.cloneElement 使用更新的道具制作新元素。该元素是由 Seven 创建的。

Here's a full working example.

这是我的代码:

var Thead = React.createClass({
  displayName: 'Thead',
  propTypes: function () {
    return {
      children: React.propTypes.node
    }
  },
  componentWillMount: function () {
    this.childTr = containsElement('tr', this.props.children)
    this.props.children = reconcileChildren('th',
      (this.childTr) ? this.childTr.props.children : this.props.children,
      this.props.data
    )
  },
  render: function () {
    return (
      <thead>
        {this.childTr ? <tr {...this.childTr.props}>
          {this.props.children}
        </tr> : <tr>
          {this.props.children}
        </tr>}
      </thead>
    )
  }
})

【问题讨论】:

  • this.props.children = reconcileChildren,您正在更改此行上的 prop,强烈建议不要这样做。道具只能由父母传递,您可能必须使用其他东西来存储这些孩子。
  • reconcileChildren 是否只是在this.props.childrenthis.childTr.props.children 之间进行选择?
  • @DavinTryon 不,这不是因为它的完整输出,您可以查看here

标签: javascript reactjs


【解决方案1】:

正如@fuyushimoya 在 cmets 中所说,不鼓励更改 props(我不知道)我将孩子设置为 this.children

var Thead = React.createClass({
  displayName: 'Thead',
  propTypes: function () {
    return {
      children: React.propTypes.node
    }
  },
  componentWillMount: function () {
    this.childTr = containsElement('tr', this.props.children)
    this.children = reconcileChildren('th',
      (this.childTr) ? this.childTr.props.children : this.props.children,
      this.props.data
    )
  },
  render: function () {
    return (
      <thead>
        {this.childTr ? <tr {...this.childTr.props}>
          {this.children}
        </tr> : <tr>
          {this.children}
        </tr>}
      </thead>
    )
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2018-07-26
    • 2020-03-04
    • 1970-01-01
    • 2018-09-06
    • 2021-05-03
    相关资源
    最近更新 更多