ReactJS 组件似乎没有独立的作用域

ReactJS component doesn't seem to have isolated scope

我是 ReactJS 的新手,来自 AngularJS。我想要一个带有按钮的组件,当您单击该按钮时,它会显示一个文本区域。在 React 中给出这个自定义组件:

Toggle = React.createClass({
    UI: {
        showNotes: false
    },
    toggleShowNotes: function () {
        this.UI.showNotes = !this.UI.showNotes;
        console.log(this.UI.showNotes);
        this.setState({UI: this.UI});
    },
    render: function () {
        return (
            <div className="well">
                <div className="form-group">
                    <button className="btn btn-default" onClick={this.toggleShowNotes}>+ Add Notes</button>
                </div>
                {this.UI.showNotes ? <textarea className="form-control" placeholder="Notes"></textarea> : null }
            </div>
        )
    }
});

请注意,只要单击按钮,我就会将组件 UI.showNotes 的状态记录到控制台。如果我将这些组件中的几个放入我的主应用程序中,如下所示:

var App = React.createClass({
  render: function () {
    return (
      <div>
        <Toggle></Toggle>
        <Toggle></Toggle>
        <Toggle></Toggle>
        <Toggle></Toggle>
        <Toggle></Toggle>
      </div>
    );
   }
});

ReactDOM.render(
        <App/>,
        document.getElementById('container')
    );

当我单击 button 时,记录到控制台的值始终与之前记录到控制台的值相反。 问题是无论我点击哪个 <Toggle> 按钮都是如此。 换句话说,似乎只有一个 this.UI 实例而不是每个组件一个实例。这让我很困惑,given ReactJS' documentation on the matter:

React takes care of creating an instance for every class component, so you can write components in an object-oriented way with methods and local state, but other than that, instances are not very important in the React’s programming model and are managed by React itself.

我希望 this.UI 对于每个组件都是唯一的,而不是在组件的所有实例之间共享的 "global" 对象。

  1. 为什么不是这样?
  2. 既然不是这样,那么重组我的组件以达到预期效果的最佳方法是什么?

通过使用

UI: {
    showNotes: false
},

你实际上是在创建一个在所有实例之间共享的对象,因为它是在原型上定义的,因此如果你更改 showNotes,所有实例都会看到更改 它与 React 无关,但与 JavaScript.

而是使用这样的东西:

Toggle = React.createClass({
    getInitialState: function() {
        return {showNotes: true};
    },
    toggleShowNotes: function () {
        this.setState({showNotes: !this.state.showNotes});
    },
    render: function () {
        return (
            <div className="well">
                <div className="form-group">
                    <button className="btn btn-default" onClick={this.toggleShowNotes}>+ Add Notes</button>
                </div>
                {this.state.showNotes ? <textarea className="form-control" placeholder="Notes"></textarea> : null }
            </div>
        )
    }
});