在 ReactJS 中单击外部时更新输入框

问题描述

我正在尝试更新数据库。所以我有一个认禁用的输入字段。因此,当您单击时,会启用编辑,而当您在输入字段外单击时,它会再次被禁用。我想要做的是当您在输入字段外单击时进行更新。所以,我的输入是这样的:

const InputPrice = ({ mainPricePosts,handleChange }) => {
  const [disabled,setdisabled] = useState(true);
  const [priceValue,setPriceValue] = useState(mainPricePosts);

  function handleClick() {
    if (disabled === true) {
      setdisabled(false);
    }
  }

  return (
    <>
    <Form.Control
      type="text"
      className="price_coefficient_input"
      value={priceValue}
      onBlur={() => {
        setdisabled(true);
        handleChange(priceValue);
      }}
      onChange={handleChange(mainPricePosts)}
      readOnly={disabled}
      onClick={handleClick}
    />
    </>
  );
};

InputPrice.propTypes = {
  mainPricePosts: PropTypes.object.isrequired,handleChange: PropTypes.func.isrequired,};

export default InputPrice;

这就是我尝试更新的方式,但我不确定从输入字段中获取值是否正确:

const [updatePosts,setUpdatePosts] = useState([]);
  const [loading,setLoading] = useState(false);
  const [error,setError] = useState(false);
  const [show,setShow] = useState(false);
  const [showError,setShowError] = useState(false);
  const handleClose = () => setShow(false);
  const handleCloseError = () => setShowError(false);

  const fetchindividualPosts = async ({ value,post: { mainPricePosts,key } = {} }) => {
    console.log(value);
    try {
      setLoading(true);
      const res = await Axios({
        method: "POST",url: `url`,headers: {
          "content-Type": "application/json",},data: {
          updated_parameter: ["main_price","small_car",key],updated_value: value,});
      if (res.status === 200) {
        setUpdatePosts(res.data);
      }
      setLoading(false);
    } catch (err) {
      console.log(err.response.status);
      setError(err.response.data.error);
      setLoading(false);
    }
  }; 

  const handleChange = (mainPricePosts) => (e) => {
    fetchindividualPosts({ mainPricePosts,value: e.target.value });
  };

这也是我更新数据的 curl 方法

curl -L -i -H "Content-Type: application/json" -X POST -d '{
              "updated_parameter":["100"],"updated_value":"0.044"
      }'  $ip''

所以 updated_value 应该是更新后的输入(点击之后的值,外部被点击) 100,应该是输入值的key。

希望你能帮我解决这个问题。

预先感谢您的帮助。

解决方法

有很多方法可以实现您的需求,但我会使用以下方法。

InputPrice 事件的 onBlur 组件中,我将通过调用 setDisabled(true) 禁用输入,然后使用 useEffect 钩子调用 handleChange 回调(如果有新的价格值)和原价不同。因为您正在调用 setDisabled(true),所以您实际上是在重新渲染您的 InputPrice 组件,因此不会执行 handleChange 回调。

下面的结帐代码。

  const InputPrice = ({ mainPricePosts,handleChange }) => {
  const [disabled,setDisabled] = useState(true);
  const [priceValue,setPriceValue] = useState(mainPricePosts);

  function handleClick() {
    if (disabled === true) {
      setDisabled(false);
    }
  }
  
 useEffect(() => {
    let callUpdateCallback = false;
    if (priceValue !== mainPricePosts) callUpdateCallback = true;
    if (disabled && callUpdateCallback) handleChange(priceValue);
 },[disabled,priceValue,handleChange,mainPricePosts]);

  return (
    <>
    <Form.Control
      type="text"
      className="price_coefficient_input"
      value={priceValue}
      onBlur={setDisabled(true)}
      onChange={(e) => setPriceValue(e.target.value)}
      readOnly={disabled}
      onClick={handleClick}
    />
    </>
  );
};

InputPrice.propTypes = {
  mainPricePosts: PropTypes.object.isRequired,handleChange: PropTypes.func.isRequired,};

export default InputPrice;

你这样调用这个组件

import React from "react";
import ReactDOM from "react-dom";
import InputPrice from "./InputPrice";

function App() {
  const handleChange = (e) => {
    console.log("app handle change",e);
    // You can call your fetch here...
  };
  return (
    <div>
      <InputPrice mainPricePosts="500" handleChange={handleChange} />
    </div>
  );
}

ReactDOM.render(<App />,document.querySelector("#root"));

此外还有用于调试它的代码和框,因此如果您需要更多详细信息,可以在下面的链接中找到它。

https://codesandbox.io/s/reactjs-playground-forked-8vwe2?file=/src/index.js:0-364