处理 FormControl React 钩子的变化

时间:2021-02-28 09:00:24

标签: javascript reactjs react-native

这是我无法在表单控件中设置状态值的 Textarea 示例,.. 我无法保存状态值,

<Form.Group controlId="exampleForm.ControlTextarea1">
   <Form.Control className="textarea" 
              value={selectDesc} 
              as="textarea"
              rows={7} 
              onChange={(event)=>setSelectDesc(event.target.value)}>
  </Form.Control> </Form.Group>

outout of the screen ,..

1 个答案:

答案 0 :(得分:0)

这是一个关于如何实现这一点的示例(我使用了 <input> 标签,但对于来自 react-bootstrap 的 <Form /> 会有相同的结果):

import { useState } from "react"; // import useState

export default function App() {
  const [name, setName] = useState(""); // useState hook

  // handle change event
  const handleChange = (e) => {
    e.preventDefault(); // prevent the default action
    setName(e.target.value); // set name to e.target.value (event)
  };

  // render
  return (
    <div>
      <input value={name} type="text" onChange={handleChange}></input>
      <p>{name}</p>
    </div>
  );
}

我做了一个处理函数,让代码更简洁一点,不要忘记阻止默认操作并设置值。

这将是使用 react-bootstrap

的结果
import { useState } from "react"; // import useState
import { Form } from "react-bootstrap";

export default function App() {
  const [name, setName] = useState(""); // useState hook

  // handle change event
  const handleChange = (e) => {
    e.preventDefault(); // prevent the default action
    setName(e.target.value); // set name to e.target.value (event)
  };

  // render
  return (
    <div>
      <Form>
        <Form.Group>
          <Form.Control
            value={name}
            type="text"
            onChange={handleChange}
          ></Form.Control>
        </Form.Group>
      </Form>
      <p>{name}</p>
    </div>
  );
}

查看我的沙盒 here