【问题标题】:Update input box when outside is clicked in ReactJS在 ReactJS 中单击外部时更新输入框
【发布时间】:2021-09-10 14:03:57
【问题描述】:

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

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。

希望很清楚,您可以帮助我解决这个问题。

提前感谢您的帮助。

【问题讨论】:

  • 下面的答案对你有用吗?

标签: reactjs fetch fetch-api inputbox


【解决方案1】:

有很多方法可以实现你所需要的,但我会使用以下方法。

onBlur 事件的InputPrice 组件中,如果新价格值和原始价格值不同,我将通过调用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

【讨论】:

  • 我可以有机会测试你的答案。但它说“错误:重新渲染过多。React 限制渲染次数以防止无限循环。”
  • 您是在代码中测试还是使用我上面提供的代码框链接进行测试?我刚刚尝试了codesandbox,它工作正常。如果您正在尝试使用您的代码,您可能会在其他地方遇到问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多