0

我想在搜索组件中进行特定的计算。为此,我必须将在 Header 组件中获得的 buttonSearchRefOffsetLeftValue 传递给 Search 组件。我在标题中获得了所需的值。但是,在 Search 组件中,它总是未定义。无法理解这种行为。

const Header = props => {
     const buttonSearchRef = useRef(null);

     let buttonSearchRefOffsetLeftValue;

     useEffect(() => {
         buttonSearchRefOffsetLeftValue = 
         ReactDOM.findDOMNode(buttonSearchRef.current).offsetLeft;
         console.log(buttonSearchRefOffsetLeftValue); //got the value
      })

   return (
      <div ref={buttonSearchRef}>He<div>
             <Search buttonSearchRefOffsetLeftValue= 
          {buttonSearchRefOffsetLeftValue} />
       ) 
     }

 const Search = (props) => {
     console.log(props.buttonSearchRefOffsetLeftValue)//got undefined WHY?
 }
4

2 回答 2

2

原因是当你像这样首先声明它时,它的值默认是未定义的

 let buttonSearchRefOffsetLeftValue;

然后,它会在of运行之前先将此值传递给Search组件。这就是你得到. 之后,当 DOM 完全渲染后,附加了 ref,useEffect 运行并更新,但这不是React 状态或道具。因此,它没有更新,导致它仍然保持未定义。useEffectHeaderundefinedbuttonSearchRefOffsetLeftValueprops.buttonSearchRefOffsetLeftValueSearch

一个快速的解决方法是进入buttonSearchRefOffsetLeftValue一个状态

export const Header = (props) => {
  const buttonSearchRef = useRef(null);

  const [ buttonSearchRefOffsetLeftValue, setButtonSearchRefOffsetLeftValue] = useState(null);

  useEffect(() => {
      setButtonSearchRefOffsetLeftValue(ReactDOM.findDOMNode(buttonSearchRef.current).offsetLeft);
      console.log('head', buttonSearchRefOffsetLeftValue); //got the value
  });

  return (<div>
    <div ref={buttonSearchRef}>He</div>
    <Search buttonSearchRefOffsetLeftValue={buttonSearchRefOffsetLeftValue}/></div>);
  }

现在您的Search组件应该记录控制台两次,第二次打印出值。

于 2020-10-13T17:28:06.840 回答
1

你可能已经注意到了。控制台日志将按如下顺序打印:

不明确的

0

这意味着useEffect总是在return函数之后调用。我建议你应该有状态buttonSearchRefOffsetLeftValue来传递它的子组件。将您的变量依赖项buttonSearchRefOffsetLeftValue放入useEffect.

我的演示:

const Search = (props) => {
    console.log('value'+ props.buttonSearchRefOffsetLeftValue)//got undefined WHY?
    return <div/>
}

const Header = props => {
    const buttonSearchRef = useRef(null);

    const [buttonSearchRefOffsetLeftValue, setButtonSearchRefOffsetLeftValue] = useState(null);

    useEffect(() => {
        let buttonSearchRefOffsetLeftValue = ReactDOM.findDOMNode(buttonSearchRef.current).offsetLeft;
        setButtonSearchRefOffsetLeftValue(buttonSearchRefOffsetLeftValue);
        console.log(buttonSearchRefOffsetLeftValue); //got the value
    }, [
        //put some dependencies will effect your buttonSearchRefOffsetLeftValue
    ])

    return <div>
            <div ref={buttonSearchRef}>He</div>
            <Search buttonSearchRefOffsetLeftValue={buttonSearchRefOffsetLeftValue} />
        </div>;
}
于 2020-10-13T17:24:21.717 回答