首页 > 解决方案 > 从输入组件中获取值并在 React 中的另一个组件中使用它

问题描述

我是 React 的新手,并且有这个简单的代码示例,我只需要从输入中获取值并将值显示回来。

    class App extends React.Component {

      constructor(props){
        super(props);
        this.state = { word : ""};
        this.onClick = this.onClick.bind(this);
      }

      onClick(e){
        this.setState({word : /* how to obtain input value?? */});
      }

      render() {
        return (
          <>
            <form>
                <input type="text"/>
                <button onClick={this.onClick}>Say it!</button>
            </form>
            <div>
              {this.state.word}
            </div>
          </>
        );
      }
    }

我知道反应希望我使用组件状态作为将信息从父组件传播到其子组件的一种方式。我不知道我应该如何获得一个孩子的状态以用于另一个孩子

我相信这应该以简单的方式做出反应,因为使用纯 DOM 或 JQuery 的等效方式也非常简单(一两行代码)。

标签: reactjs

解决方案


您可以使用createRef

import React, { createRef } from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { word: "" };
    this.onClick = this.onClick.bind(this);
  }
  textInput = createRef();
  onClick(e) {
    this.setState({ word: this.textInput.current.value });
  }

  render() {
    return (
      <div className="App">
        <form>
          <input ref={this.textInput} type="text" />
          <button onClick={this.onClick} type="button">
            Say it!
          </button>
        </form>
        <div>{this.state.word}</div>
      </div>
    );
  }
}
export default App;

在这里检查CodeSandBox


推荐阅读