繁体   English   中英

如何从按钮单击事件中获取输入值?

[英]How can I get the value of an input from a button click event?

我想将文本输入上的值连接到 state 中的属性,但我不知道如何从单击事件访问该输入的值。

这是我现在正在使用的代码。

  onCreateClick = () => {
    const valueFromInput = 

    this.setState((prevState) => {
      stateProperty: prevState.stateProperty.concat(`${valueFromInput}`)
    })
  }

这是一个如何做到这一点的例子,我使用了功能组件和钩子而不是基于类的组件,但我希望你能理解实现背后的逻辑:

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

export default function App() {
  const [stateProperty, setStateProperty] = useState("");
  const [valueFromInput, setValueFromInput] = useState("");

  const onCreateClick = () => {
    let newString = stateProperty;
    setStateProperty(newString.concat(valueFromInput));
    setValueFromInput("");
    console.log(valueFromInput);
  };
  return (
    <div className="App">
      {stateProperty ? stateProperty : "Type Something"}
      <input
        value={valueFromInput}
        onChange={(e) => setValueFromInput(e.target.value)}
      />
      <button onClick={onCreateClick}>append</button>
    </div>
  );
}

代码沙盒示例

您可以在要获取其值的 JSX 元素上设置引用。 然后您可以在事件处理程序中引用 DOM 元素。 一旦你有了对该 DOM 元素的引用,你就可以像普通的 HTML 元素一样使用yourElement.value获取输入的值。

https://reactjs.org/docs/refs-and-the-dom.html

从 React 文档复制

带有 Hooks 的功能组件

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  const textInput = useRef(null);
  
  function handleClick() {
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

class 组件实现

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM