我正在学习ReactJS,我想了解如何使用简单的onclick事件获取ReactJS中的输入文本值.虽然我能够获得文本输入的参数,但我还是遵循了教程.但不知何故,我无法得到它的价值.

var MyComponent = React.createClass({
  handleClick: function() {
    if (this.refs.myInput !== null) {
        var input = this.refs.myInput;
            var inputValue = input.value;
      alert("Input is", inputValue);
    }
  },
  render: function() {
    return (
      <div>
        <input type="text" ref="myInput" />
        <input
          type="button"
          value="Alert the text input"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

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

这里是同样的JSFIDLE:jsfiddle link

推荐答案

首先,不能传递到alert秒的参数,而是使用串联

alert("Input is " + inputValue);

Example

然而,为了更好地从输入中获取值,可以使用这样的状态

var MyComponent = React.createClass({
  getInitialState: function () {
    return { input: '' };
  },

  handleChange: function(e) {
    this.setState({ input: e.target.value });
  },

  handleClick: function() {
    console.log(this.state.input);
  },

  render: function() {
    return (
      <div>
        <input type="text" onChange={ this.handleChange } />
        <input
          type="button"
          value="Alert the text input"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

ReactDOM.render(
  <MyComponent />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Reactjs相关问答推荐

无法使用#13;或br将新行设置为文本区域'"&"<>

在Reaction中测试条件组件

有没有办法在Shopify中显示自定义计算的交货日期?

在Reaction中单击并显示子组件延迟/动画

react ';S使用状态不设置新状态

悬停轴时重新绘制自定义参照线

状态改变不会触发重新渲染

从 MongoDB createAt 字段中分割精确时间

如何使用 App Router 和服务器组件在 Next.js 13 中实现分页

未捕获的运行时错误:对象作为 React 子项无效

在遵循 react-navigation 的官方文档时收到警告消息

使用 MuiCssBaseline 在所有 MUI v5 标签上设置边距 0

如何实现 redux 工具包来注册用户?

Redux Toolkit 配置,是否适用于全栈应用程序?

为嵌套路由配置一个不存在的 url 的重定向

将props 传递给 NextJS 布局组件

使用 Vite 的 React 中的路由无法正常工作(构建中)

如何通过onpress on view in react native flatlist来降低和增加特定视图的高度?

React + i18next + Trans + Prettier:Prettier 最终会在重新格式化 JSX 时 destruct 翻译

如何在 React 中单击鼠标的位置动态添加 div?