如何在 ReactJS 中查询字段值?

How does one query a field value in ReactJS?

我的代码目前正在直接访问 React 组件,并收到一条警告说 "You probably don't want to do this." 代码是:

var description = document.getElementById('description').value;
console.log(description);
new_child.setState({
    description: description
});

它试图访问的组件是:

var that = this;
return (
    <table>
        <tbody>
            {that.state.children}
        </tbody>
        <tfoot>
            <td>
                <textarea className="description"
                          placeholder=" Your next task..."
                          onChange={that.onChange} 
                          name="description"
                          id="description"></textarea><br />
                <button onClick={that.handleClick}
                        id="save-todo">Save</button>
            </td>
        </tfoot>
    </table>
    );

用 "thinking in React" 替换代码替换我这里的代码的惯用方法是什么?

我在这里称自己为完全的新手,但看着这段代码 https://github.com/abdullin/gtd/blob/master/web/components/TaskComposer.jsx

您应该能够绑定到文本区域值:

<textarea id="description" 
          value={that.state.text} ...

然后您可以像这样在点击处理程序中提取值:

var description = this.state.text;

让我知道这是否有效:)

更新

刚刚查看了 React 主页 (https://facebook.github.io/react/),第三个示例 应用程序 似乎也遵循这种模式

var TodoList = React.createClass({
  render: function() {
    var createItem = function(itemText, index) {
      return <li key={index + itemText}>{itemText}</li>;
    };
    return <ul>{this.props.items.map(createItem)}</ul>;
  }
});
var TodoApp = React.createClass({
  getInitialState: function() {
    return {items: [], text: ''};
  },
  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.text]);
    var nextText = '';
    this.setState({items: nextItems, text: nextText});
  },
  render: function() {
    return (
      <div>
        <h3>TODO</h3>
        <TodoList items={this.state.items} />
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (this.state.items.length + 1)}</button>
        </form>
      </div>
    );
  }
});

React.render(<TodoApp />, mountNode);

所以为了回答你的问题,我认为 React 做事情的方式是 bindthis.state.

您应该使用 refs 属性。 所以假设你有一个看起来像 this:

的渲染方法
render: function () {
    <MyTextBox ref="myText" />
    <div>Some other element</div>
}

现在假设渲染的 MyTextBox 元素有一个 expode() 方法。您可以使用以下方式调用它:

this.refs.myText.explode()

本质上,refs 上面有一个 属性 myText,因为在渲染期间,您通过编写 ref="myText" 为其提供了一个引用名称 您可以找到更多信息 here