重用反应组件

Reusing react component

我对组件反应的使用有一些疑问。 基本上我想在代码的各个部分使用 "Title" 组件,但它总是有 "states" 变化。官方文档对这个问题我不是很理解,因为我继承了这个组件,只把"states"改成我想要的? 我知道这个问题看起来很愚蠢,但我正在学习,React 与我所看到的一切都非常不同。

var Title = React.createClass({
  displayName: "Title",
  getDefaultProps: function () {
    return {
      className: ""
    }
  },
  render: function () {
    return <h1 className={this.props.className}>{this.state.content}</h1>
  }
});

您可能希望将 {this.state.content} 替换为 {this.props.children} 并像这样使用您的组件:

<Title className="myclass">my title</Title>

作为一般规则,尽可能避免使用状态,哑组件更容易重用。

在这种情况下,您应该使用 props 而不是 state。 Props 归 parents 所有,state 归组件本身所有。既然你想在多个地方使用这个组件,那么自然地 parent 将决定标题的文本应该是什么 - 因此道具就是你想要的。

React 有一个特殊的 prop children,它接受在内部组件的 JSX 标签中传递的任何值。

例如,这是一个多次使用您的 Title 组件的模拟组件:

var MyComponent = React.createClass({

  render: function() {
    return (
      <div>
        <Title className="foo">Hello</Title>
        <Title className="bar">World</Title>
      </div>
    );
  }

});

由于您现在将文本作为 children 属性传递给组件,因此您必须更新 Title 组件以呈现此内容:

var Title = React.createClass({
  displayName: "Title",
  getDefaultProps: function () {
    return {
      className: ""
    }
  },
  render: function () {
    // NOTE: we are now using children prop
    return <h1 className={this.props.className}>{this.props.children}</h1>
  }
});

这样做的一个附带好处是您可以构建更复杂的标题,包含多个 children,并且它会正常工作:

var MyOtherComponent = React.createClass({

  render: function() {
    return (
      <div>
        <Title className="foo">
          <span>Hello</span>
          <a href="bar.html">World</a>
        </Title>
      </div>
    );
  }

});