【问题标题】:Two way data binding in React with HooksReact with Hooks 中的两种数据绑定方式
【发布时间】:2020-04-29 17:31:06
【问题描述】:

我正在使用 React 构建一个应用程序,其中两个组件应该能够改变彼此的状态:

组件 A -> 组件 B

组件 B -> 组件 A

组件 A 是一组按钮,组件 B 是一个输入元素。

我设法让它只以一种方式工作,A -> B 或只是 B -> A,但不能让它同时工作。它部分使用 useEffect 钩子,但有错误,我认为这是一个非常愚蠢的想法。

我读过很多关于 React 不能以这种方式工作的文章,但是有什么迂回的方法可以使它工作吗?我的应用程序确实需要这种 2 向数据绑定。

感谢您的帮助!

按钮的状态位于自定义上下文挂钩 (useStateContext) 中的 digits 变量中作为数组。

import { useStateContext } from "components/StateProvider/Context"; 
import { useState, useEffect } from "react";

import { baseConvert } from "utility/baseConvert";

const NumberInput = () => {

  const [ { digits, baseIn, baseOut }, dispatch ] = useStateContext();

  const convertedValue = baseConvert({
    digits,
    baseIn,
    baseOut
  });

  const [ inputValue, setInputValue ] = useState(convertedValue);

  /* useEffect(() => {
    setInputValue(convertedValue)
  }, [ digits, baseIn, baseOut ]) */

  const regex = /^[A-Z\d]+$/;

  const handleInput = ({ target: { value }}) => {
    if (value === "") setInputValue(0);

    console.log(value);

    if (regex.test(value)) {
      setInputValue(value);
      dispatch({
        type: "setDigits",
        digits: baseConvert({
          digits: value.split("").map(Number),
          baseIn: baseOut,
          baseOut: baseIn
        })
      })
    }    
  };

  return (
    <input type="text" onChange={handleInput} value={inputValue} />
  );
};

export default NumberInput;

【问题讨论】:

    标签: reactjs react-hooks react-state-management


    【解决方案1】:

    组件不应直接操纵其他组件的状态。如果您需要共享数据,请将状态带到父组件并将回调传递给可以更改状态的子组件。

    例如:

    function ParentComponent() {
      const [currentVal, setCurrentVal] = useState(0);
      return
       <>
         <Child1 value={currentVal} onChange={setCurrentVal}/>   // you might also pass a function that does some other logic and then calls setCurrentVal
         <Child2 value={currentVal} onChange={setCurrentVal}/>
       </>
    }
    

    【讨论】:

    • 明白。好吧,我会尝试将我的状态分成两个状态部分。感谢您的回复!
    • 看来 currentVal 对两个孩子来说都是一样的
    【解决方案2】:

    @Jeff Storey 解决方案似乎有点错误。第一个索引是值,第二个索引是更新值的函数。

    应该是:

    const [currentVal, setCurrentVal] = useState(0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-27
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2014-02-25
      相关资源
      最近更新 更多