如何在 React.js 中重用这一小块代码?

How to reuse this little block of code in React.js?

我是一个新手,但这是我的代码:

var ExampleComponent = React.createClass({
  getInitialState: function() {
    return {close: false};
  },
  handleClick: function(event) {
    this.setState({close: !this.state.close});
  },
});

  var ButtonThing = React.createClass({
   <ExampleComponent />,
   render: function() {
    <div> yo </div>
    );
  }
 });

哪里的"ExampleComponent"可以在多个地方使用?我已经尝试了上面的方法,只是直接输入 "ExampleComponent",但没有运气。还是我做错了?

React 中的代码重用由称为 mixins 的概念促进。

react docs举个简洁的例子

针对您的情况

var exampleMixin = {
  getInitialState: function() {
   return {close: false};
  },
  handleClick: function(event) {
    this.setState({close: !this.state.close});
  }
}
var ButtonThing = React.createClass({
  mixins: [exampleMixin], // Use the mixin
  render: function() {
    return (<div> yo </div> );
  }
 });

因为你正在使用 React.createClass 你可以尝试使用 mixins,像这样

var ComponentStateMixin = {
  getInitialState: function() {
    return { close: false };
  },

  handleClick: function(event) {
    this.setState({ close: !this.state.close });
  }
};

var ButtonThing = React.createClass({
  mixins: [ ComponentStateMixin ],
  render: function() {
    return <div>
      <button onClick={ this.handleClick }>Close</button>
      <p>{ 'ButtonThing state:: ' + this.state.close }</p>
    </div>;
  }
});

var Modal = React.createClass({
  mixins: [ ComponentStateMixin ],
  render: function() {
    return <div>
      <button onClick={ this.handleClick }>Close Modal</button>
      <p>{ ' Modal state:: ' + this.state.close }</p>
    </div>;
  }
});

Example