在 React 中使用 onChange 修改 Textarea 的值

在 React 中使用 onChange 修改 Textarea 的值

Modify the value of a Textarea using onChange in React

在 React 中使用 onChange 修改文本区域的值:

  1. 向文本区域添加一个onChange道具,将其设置为一个函数。
  2. useState通过钩子将文本区域的值存储在状态中。
  3. 每次用户在文本区域中键入时更新状态变量。
应用程序.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleMessageChange = event => { // 👇️ update textarea value setMessage(event.target.value); console.log(event.target.value); }; return ( <div> <label htmlFor="message">My Textarea</label> <textarea id="message" name="message" value={message} onChange={handleMessageChange} /> </div> ); }; export default App;

我们使用useState
挂钩将 textarea 元素的值存储在组件的状态中。

我们将一个函数传递给onChangetextarea 的属性,因此每次用户在该字段中键入内容时,handleMessageChange都会调用该函数。

反应获取textarea的价值

我们可以访问事件对象上 textarea 元素的值作为
event.target.value

事件的target属性是对 textarea 元素的引用。

设置文本区域的值后,您可以使用
message状态变量访问它。

您可能会在 React 中看到的另一种选择是通过
ref.

应用程序.js
import {useRef} from 'react'; const App = () => { const ref = useRef(null); const handleClick = event => { // 👇️ access textarea value console.log(ref.current.value); }; return ( <div> <label htmlFor="message">My Textarea</label> <textarea ref={ref} id="message" name="message" /> <button onClick={handleClick}>Click</button> </div> ); }; export default App;

获取文本区域值参考

每次单击按钮时,textarea 的值都会被记录到控制台。

请注意,我们没有在元素上使用onChangeprop 。textarea对于不受控制的字段,我们不会在每次击键时跟踪字段的值,而是在需要时访问它。

useRef ()钩子可以传递一个初始值作为参数。该钩子返回一个可变的 ref 对象,其.current属性被初始化为传递的参数。

请注意,我们必须访问currentref 对象上的属性才能访问我们设置prop 的 textarea 元素。 ref

当我们将 ref prop 传递给元素时,例如<textarea ref={myRef} />,React 将.currentref 对象的属性设置为相应的 DOM 节点。

useRef钩子创建了一个普通的 JavaScript 对象,但在每次渲染时都会为您提供相同的 ref 对象。换句话说,它几乎是一个带有.current属性的记忆对象值。

您可以通过访问 textarea 元素上的任何属性ref.current如果您记录对象的current属性ref,它只是对
textarea元素的引用。