我可以通过函数组件传递 ref 吗?

Dev*_*hod 4 dom components function reactjs

-我正在使用功能组件。- 现在我在这里使用 3 个组件,其中一个是父组件,另外 2 个是子组件。- 我需要访问一个子组件方法或状态到另一个子方法。我已经使用CreateRef完成了类组件,但现在我需要使用函数组件,但我在“ref.current”中得到 Null。

export function SideBySideList(props) {
    const ref = React.createRef();

	//this is call inside ListPage after sucess
    function updateRightList(id) {
        ref.current.state.actualSearchedModel.Id = id
        ref.current.fetchDataAndUpdate();
    }
    function itemClicked(id) {
        updateRightList(id);
    }
    return (
        <>
            <div className="col-12 no-padding">
                <div className={props.leftListLayoutClass}>
                    <ListPage
					    updateRightList={updateRightList}
					/>
                </div>
                <div className={props.rightListLayoutClass}>
                    <ListPage
                        ref={ref}
                    />
                </div>
            </div>
        <>
    );
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*aev 6

根据官方文档:

你不能在函数组件上使用 ref 属性,因为它们没有实例

因此,如果您ListPage是功能组件,则必须将其转换为类组件。或者你的 ref 必须引用ListPage.

function ListPage ({ref}) {
  return <div ref={ref}>Hello!</div>
}
Run Code Online (Sandbox Code Playgroud)

更新:

function ListPage ({ref}) {
  return <div ref={ref}>Hello!</div>
}
Run Code Online (Sandbox Code Playgroud)
function ParentComponent () {
  const [state, setState] = React.useState(null);
  
  const onChildMount = React.useCallback((dataFromChild) => {
    setState(dataFromChild);
  });
  
  return (
    <div>
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <ChildComponent onMount={onChildMount} />
    </div>
  )
}

function ChildComponent (props) {
  const thisShouldBePassedToTheParent = "from child with love";
  
  React.useEffect(() => {
    props.onMount(thisShouldBePassedToTheParent);
  }, []);
  
  return (
    <div>child component</div>
  )
}

ReactDOM.render(<ParentComponent />, document.querySelector("#root"));
Run Code Online (Sandbox Code Playgroud)